Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 913
Richard Knop Avatar asked Apr 18 '13 13:04

Richard Knop


People also ask

How to get height and width of image in jQuery?

var imageWidth = $(Imgsize). width(); alert(imageWidth);

How to find the height of the image using jQuery?

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.

How to get image width and height in JS?

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.


1 Answers

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.

like image 82
ahren Avatar answered Jan 01 '23 20:01

ahren