Are there any JavaScript or jQuery APIs or methods to get the dimensions of an image on the page?
I think an update to these answers is useful because one of the best-voted replies suggests using clientWidth
and clientHeight, which I think is now obsolete.
I have done some experiments with HTML5, to see which values actually get returned.
First of all, I used a program called Dash to get an overview of the image API.
It states that height
and width
are the rendered height/width of the image and that naturalHeight
and naturalWidth
are the intrinsic height/width of the image (and are HTML5 only).
I used an image of a beautiful butterfly, from a file with height 300 and width 400. And this Javascript:
var img = document.getElementById("img1");
console.log(img.height, img.width);
console.log(img.naturalHeight, img.naturalWidth);
console.log($("#img1").height(), $("#img1").width());
Then I used this HTML, with inline CSS for the height and width.
Results:
/*Image Element*/ height == 300 width == 400
naturalHeight == 300 naturalWidth == 400
/*Jquery*/ height() == 120 width() == 150
/*Actual Rendered size*/ 120 150
I then changed the HTML to the following:
i.e. using height and width attributes rather than inline styles
Results:
/*Image Element*/ height == 90 width == 115
naturalHeight == 300 naturalWidth == 400
/*Jquery*/ height() == 90 width() == 115
/*Actual Rendered size*/ 90 115
I then changed the HTML to the following:
i.e. using both attributes and CSS, to see which takes precedence.
Results:
/*Image Element*/ height == 90 width == 115
naturalHeight == 300 naturalWidth == 400
/*Jquery*/ height() == 120 width() == 150
/*Actual Rendered size*/ 120 150