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
});
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.
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.
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.
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.
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