Search code examples
jqueryhtmldynamicdynamic-data

Dynamically loaded image returning outerHeight of 0 (jQuery)


It seems that for some reason the .load method is not working. here in my jquery:

$(document).ready(function() {
    var imgHeight;
    $('body').prepend('<img src="http://farm9.staticflickr.com/8266/8653931785_4a8d43164f.jpg" class="select" />');
    if($('img.select').prop('complete')) {
       imgHeight = $('img.select').outerHeight();
    }else{
        $('img.select').load(function() {
            imgHeight = $('img.select').outerHeight();
        });    
    }
    $('body').prepend('<p>Image Height: ' + imgHeight + '</p>');
});

and a link to a jsfiddle

After the example is run a couple times(and I assume the image is cached) it will successfully retrieve the correct height. This tells me that if($('img.select').prop('complete')) is working properly.

What am I missing here?

(tested in Chrome and FF)

EDIT: Alright, now what if I want to check more than one image if they are loaded? $('img.select').prop('complete') only tests the first element that matches the selector. http://jsfiddle.net/hcarleton/2Dx5t/6/


Solution

  • Edit Updated to use one() instead of deprecated load()

    load() is aysnchronous, so will not set the value of imgHeight before your call to $('body').prepend('<p>Image Height: ' + imgHeight + '</p>');. Also the load() event handler function is deprecated as of jQuery 1.8.

    It would be best to attach a delegated load listener to the body for any images with the .select class. In the callback of that event handler, you can detect the image height.

    $(document).ready(function() {
        $('body').one('load', 'img.select', function(e) {
            var imgHeight = $('img.select').outerHeight();
            $('body').prepend('<p>Image Height: ' + imgHeight + '</p>');
        });    
    
        $('body').prepend('<img src="http://farm9.staticflickr.com/8266/8653931785_4a8d43164f.jpg" class="select" />');
    });