How to Get an Images real width and height with JavaScript

Finding the width and height of an image with JavaScript can be a little tricky. If the script runs before the image is loaded, img.width will return 0. Different browsers act in different way. Hell, different browser versions act in different ways. The fool proof way to find the dimensions on an image with JavaScript lies in the Image() object. Declare it, set it’s src value to the source of your image and do all the dimensional goodness on the image in the object’s onload function. This is also a good way to get the dimensions of an image that might not be in your HTML mark-up.

1
2
3
4
5
6
var img = new Image();
img.onload = function() {
  imgW = this.width;
  imgH = this.height;
}
img.src = 'http://1.bp.blogspot.com/-APNqWMWibVo/UIJjOcaxMnI/AAAAAAAAExk/0wA50be_--k/s1600/tumblr_m5elk1kyxB1qd769xo1_500.jpg';