How do I get the width / height of an image before adding it to the DOM / Browser?


i would like to output the width and height of an image before appending that to the browser. Of course, i get 0 for the width and 0 for the height, cause the image is not appended to the DOM yet.

I have uploaded my code to

How can i take the right values before appending the image to the DOM??

Thanks, in advance!

You seem to have very interesting questions. This is my humble answer:

$(document).ready(function() {
    $(".Photos a").click(function () {
        var href_attribute = $(this).attr('href');
        var new_item = $('<img src="' + href_attribute + '" />')
            .load(function () {
                alert('Img was loaded! Width: ' + this.width + ' and height: ' + this.height);
        return false;

Live example:

You see, you must make sure that the image is preloaded, for that we use .load(). Otherwise you will get 0. That's actually good, because it means that the script works, just everything is so fast, that it can get the dimensions. .load() makes sure that the image is first loaded and only then receive the dimensions.

For whatever purposes you wanted to use the dimensions, I recommend doing that inside the .load() as well. Because you probably will have multiple .Photos a anyways.

Also, as you might have noticed your .fadeIn(2000) was not working. That's because, your item got appended before you called it. As you can see, I fixed it for you :)

NB! Sorry, I renamed some of the variables (made stuff more logic in my head.)