Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image size before is in DOM

Tags:

jquery

How can I get image size before I put it into the DOM?

var imgLoad = $("<img />");
$(imgLoad).attr("src", ImageGallery.ImagesList[index] + "?" + new Date().getTime());
$(imgLoad).unbind("load");
$(imgLoad).bind("load", function () {

   // Get image sizes
   alert(imgLoad.width()); // RETURN 0

});
like image 503
David Horák Avatar asked May 25 '11 12:05

David Horák


People also ask

How do I find out the size of an image?

You can also right-click on an image & choose properties from the drop-down menu. A new window will appear with several tabs. You'll click the details tab, and there you'll find you image size and dimensions.

Is image a DOM object?

The Image Object in HTML DOM is used to represent the HTML < image > element. This tag is used to set or get the properties of < image > element. This element can be accessed by using getElementById() method.

How do I find the size of an image in HTML?

Right-click the image whose size you want to know and select Inspect. View your image's width and height displayed in the Chrome DevTools. (Note, the first number is always the width). If your image is not highlighted by default, click the inspect element button.


1 Answers

Use imgLoad[0].width and imgLoad[0].height instead, or use this instead of imgLoad:

var imgLoad = $("<img />");
imgLoad.attr("src", ImageGallery.ImagesList[index] + "?" + new Date().getTime());
imgLoad.unbind("load");
imgLoad.bind("load", function () {

   // Get image sizes
   alert(this.width);

});

Working demo: http://jsfiddle.net/7twNk/

This works because the browser populates the height/width properties of the element when it downloads the image. jQuery, on the other hand, fetches the actual visible dimensions of the element — this will always be 0 when an element isn't displayed.

Note that you do not need to keep wrapping imgLoad with $() because it is already a jQuery object.

like image 103
Andy E Avatar answered Sep 16 '22 22:09

Andy E