Setting DIV width based on child image - javascript

I am trying to set DIV width based on the child image. This code below works if there is only one DIV. When there are more, it will only use the width of the first child image (first DIV).
$('.img_thumb').each(function(){
$('img').load(function(){
var img_width = $('.img_thumb img').width();
$('.img_thumb').css('width', img_width + 'px');
});
});
Any help would be appreciated. Thanks

In the .load() callback, use this to refer to the specific image of interest. Get rid of the .each().
$('img').load(function(){
var $this = $(this),
img_width = $this.width();
$this.closest('.img_thumb').css('width', img_width + 'px');
});

On line 3 you have a reference to the object $('.img_thumb img'):
var img_width = $('.img_thumb img').width()
Which is always going to point to the first element. You need to use $(this) when you're inside the .each in order to target the current element:
var img_width = $(this).width()

Try this:
$('.img_thumb').each(function(){
var _this = $(this);
$(this).find('img').load(function(){
_this.css('width', $(this).width() + 'px');
});
});

Related

Add width and height attr to all images

I need width and height attributes added to all images on a page via javascript/jquery. This is due to a tool our systems use. I thought a simple each loop, adding height/width attr would suffice. Unfortunately this doesn't seem to work
DEMO https://jsfiddle.net/z86xnqd7/
$('body').find('img').each(function (index) {
var theWidth = index.width();
var theHeight = index.height();
index.attr({
"width": theWidth,
"height": theHeight
});
});
When you inspect element you will notice no width/height attr has been added
jsFiddle : https://jsfiddle.net/CanvasCode/z86xnqd7/6/
You need to do your each on the load event, you need to make sure your image has loaded before you check its height and width. Also you want to use $(this) instead of index.
$(function () {
$('img').load(function () {
var theWidth = $(this).width();
var theHeight = $(this).height();
$(this).attr({
"width": theWidth,
"height": theHeight
});
});
});
It's because index is real iteration index (e.g. 1, 2...). Use $(this) or add second parameter to function header function (index, element) {}:
$.each($('img'), function () {
$(this).attr({
width: $(this).width(),
height: $(this).height()
});
});
Problem here is that you try to get the width and height from the index which is just a number and no jQuery object. Try this - it will do the job:
$('body').find('img').each(function(i, elem) {
var $this = $(this);
var theWidth = $this.width();
var theHeight = $this.height();
$this.attr({"width": theWidth, "height": theHeight});
});
See js fiddle: https://jsfiddle.net/g4nn2pk0/2/

Show current div size in html text

I try to show current the width and height of a div in another div. I use the resize: both on the div I am trying to measure. The problem I have now is that the numbers do not update when I resize the div.
$(function () {
var divheight = $("#resizediv").height();
var divwidth = $("#resizediv").width();
document.getElementById("divheightdisplay").innerHTML = divheight;
document.getElementById("divwidthdisplay").innerHTML = divwidth;
});
Fiddle
I also tried CSS Element Queries. But have some problems with overflow: hidden
The resize event does not seem to apply to elements other than the window.
Instead, you could update based on the mousemove event:
$('#resizediv').on('mousemove', function() {
var divheight = $(this).height(),
divwidth = $(this).width();
$('#divheightdisplay').html(divheight);
$('#divwidthdisplay').html(divwidth);
});
Fiddle
If the content of your divs are loaded dynamically, then you will need to use window.load event to get the correct size:
$(window).load(function() {
var divheight = $("#resizediv").height();
var divwidth = $("#resizediv").width();
document.getElementById("divheightdisplay").innerHTML = divheight;
document.getElementById("divwidthdisplay").innerHTML = divwidth;
});
You will have to call a callback function, which updates the values of width and height, on resizing your div.
//Say this is the function which is resizing your div
resize("#resizediv", callback());
function callback() {
var divheight = $("#resizediv").height();
var divwidth = $("#resizediv").width();
document.getElementById("divheightdisplay").innerHTML = divheight;
document.getElementById("divwidthdisplay").innerHTML = divwidth;
}

Get DIV width and height in javascript

I'm trying to get the div width and height as the user changes it and submit that number to another page. I can't seem to figure out how to get the width and height though.
<script>
$(function() {
$( "#set div" ).draggable({
stack: "#set div",
preventCollision: true,
containment: $('#main_content'),
stop: function(event, ui) {
var mydiv = document.getElementById("set");
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
var width = mydiv.style.width; ----THIS DOESN'T WORK
var height = mydiv.style.height; ----THIS DOESN'T WORK
var window_width = window.innerWidth;
var window_height = window.innerHeight;
var need = ui.helper.data("need");
console.log(pos_x);
console.log(pos_y);
console.log(width);
console.log(window_width);
console.log(need);
//Do the ajax call to the server
$.ajax({
type: "POST",
url: "updatecoords.php",
data: { x: pos_x, y: pos_y, need_id: need, width: width, height: height, window_width: window_width, window_height: window_height}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
});
</script>
What's the proper way to do this?
It's quite wrong to use ele.style.width to get the element's width!!!!!!
In native JavaScript, you can get a element's CSS through two ways:
Standard Method
window.getComputedStyle(ele)
For example,
var ele = document.getElementById("content"), // Do not use #
eleStyle = window.getComputedStyle(ele);
/* Below is the width of ele */
var eleWidth = eleStyle.width;
IE(IE 8 And Before)
element.currentStyle
For example,
var ele = document.getElementById("content"), // Do not use #
eleStyle = ele.currentStyle;
/* Below is the width of ele */
var eleWidth = eleStyle.width;
Why Not Use ele.style?
ele.style is just get the attribule style of ele. If you use ele.style.width, you just get the width of ele.style, not the real width of ele.
If you have done something like:
ele.style.width = "55px"
You get "55px" when using ele.style.width. If you haven't, you will get undefined.
How To Do In jQuery?
Use $ele.width() (if you want the "exact" width, use $ele.outWidth()), jQuery has done everything for you.
In plain vanilla JavaScript use
var width = mydiv.offsetWidth;
var height = mydiv.offsetHeight;
This will give you numeric values, or
var width = mydiv.offsetWidth + 'px';
var height = mydiv.offsetHeight + 'px';
If you want them in "CSS" format.
Since you're already using jQuery, you can just do:
var width;
if (need == 1) {
width = $("#web").width();
} else {
width = $("#set").width();
}
Since you're using jQuery, you'll probably want to know about the following:
$('#id').outerWidth()
$('#id').outerWidth(true)
These will come in very handy. This allows you to find the total width of the div (padding, border, width and (optional argument) margin).
http://api.jquery.com/outerWidth/

jQuery width() and height() return 0 for img element

So I am creating a new image element once I get response from AJAX call with image metadata like this:
var loadedImageContainter = $('<div class="loaded-image-container"></div>');
var image = $('<img src="' + file.url + '" alt="">');
loadedImageContainter.append(image);
$('.loading-image').replaceWith(loadedImageContainter);
var width = image.width();
var height = image.height();
console.log(width);
console.log(height);
But width() and height() functions are returning 0 although image has 30 x 30 px size and it appears correctly on the page. I need to get its dimensions in order to absolutely position the image.
You need to wait until the image has loaded to have access to the width and height data.
var $img = $('<img>');
$img.on('load', function(){
console.log($(this).width());
});
$img.attr('src', file.url);
Or with plain JS:
var img = document.createElement('img');
img.onload = function(){
console.log(this.width);
}
img.src = file.url;
Also, you don't need to insert the image into the DOM before you read the width and height values, so you could leave your .loading-image replacement until after you calculate all of the correct positions.
That is because your image isn't loaded when you check width
Try using load event this way
$('img').on('load',function(){
// check width
});
You can also use the alternate API $.load method:
$('<img src="' + file.url + '" alt="">').load( function(){ <your function implementation> });
As #ahren said earlier the reason is that image not loaded when you tring to get it's sizes.
If you want to fix this without jQuery you can use vanilla JS addEventListener method:
document.getElementsByTagName('img')[0].addEventListener('load', function() {
// ...
var width = image.width();
var height = image.height();
console.log(width);
console.log(height);
// ...
});
For me it only works with "appendTo"
$('<img src="myImage.jpeg">').load(function(){
$w = $(this).width();
$h = $(this).height();
$(this).remove()
}).appendTo("body")
Try this:
$('.loading-image').replaceWith(loadedImageContainter);
$('.loading-image').load(function(){
var width = image.width();
var height = image.height();
console.log(width);
console.log(height);
});
If you put it inside the AJAX call, that will work too, this is for json method
$.post("URL",{someVar:someVar},function(data){
var totalImgs = $('body').find('img').length;
var image = $('<img src="' + data.file[0].url + '" alt="" id="IMG_'+ totalImgs +'">');
loadedImageContainter.append(image);
$('.loading-image').replaceWith(loadedImageContainter);
var width = $('#IMG_'+totalImgs).width();
var height = $('#IMG_'+totalImgs).height();
},'json');

Get image height via JavaScript

In a JavaScript function, I want to get the height of an image. I do:
var image_height = $(image).height();
Turns out image_height is 0, but I'm sure my image doesn't have height 0. Is there a way to extract this height?
Calculate height after image load.
$(document).ready(function(){
$(image).load(function(){
var image_height = $(this).height();
} );
});
try outerHeight() as well
var image_height = $(image).outerHeight();
Make sure the dom has been rendered prior to retrieving the height.
$(document).ready(function(){
var image_height = $(image).height();
}):
You can also use regular JS:
var image_height = img.clientHeight

Categories

Resources