Get The Real Dimensions of an Image Using jQuery

Lately I have been working through a solution where I needed 'real-time' information about the dimensions of an image so I could programmatically perform resizing operations. My first approach was to use the jQuery height and width functions. But both of these methods returned 0, which is not what I needed. If the image is 94 pixels by 125 pixels I would hope to see these numbers returned by the height and width functions.

 

var

myImg = $(

"img"

);
myImg.attr(

"src"

,

"https://mydomain.com/Liberty-Bell-125.jpg"

);

alert(

"dimensions - h = "

+ myImg.height() +

"; width = "

+ myImg.width());?

http://jsfiddle.net/docluv/FzbHP/3/

While I can get the above code to work in jsFiddle, I was having issues in my application for whatever reason. I would always get 0 for both the height and the width. My suspicions lead me to believe the image I was loading in my application was either not properly cached, a little large or a combination of both. But basically I determined the code I was calling to get the image dimensions was executing before the actual image could be loaded, thus the dimensions were actually 0 x 0.

It turns out if you programmatically load an image you can get accurate dimensions once the image is loaded. The IMG tag has a load event that fires and jQuery has a simple load method to apply a callback method. If you define the image load callback function before you load the image your code gets executed when the image is available. In the following example the height and width return 94 and 125 respectively, as expected.

 

var

myImg = $(

"img"

);
myImg.on(

"load"

,

function

(e){
alert(

"dimensions - h = "

+ myImg.height() +

"; width = "

+ myImg.width());
});
myImg.attr(

"alt"

,

"The Liberty Bell"

);
myImg.attr(

"src"

,

https://mydomain.com/Liberty-Bell-125.jpg

);

http://jsfiddle.net/docluv/Q6xPd/

This IMG load event is a very handy event to leverage to make your applications more asynchronous. I use a lot of templates that are dynamically loaded as the user uses the application. I can think of many situations besides doing size manipulation where using this technique can come in handy. For example maybe there is is a need to collect or send back data, but only after the application is in a certain state. If the loaded image is the trigger you now can send back the request or data. Images may take a little longer to load because they are large or there are too many http requests in the queue and reliably knowing when they are loaded is a good thing to know to make your applications more dynamic.

Share This Article With Your Friends!