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.
var imageWidth = $(Imgsize). width(); alert(imageWidth);
Another plausible way to get the width and height of an image element in DOM is with jQuery's . width() and . height() method. Note, this will return the size of the <img> element, and not the actual height and width of the image itself.
Answer: Use the JavaScript clientWidth property You can simply use the JavaScript clientWidth property to get the current width and height of an image. This property will round the value to an integer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With