Search code examples
jqueryimageready

Consistent way of finding element height after nested image has loaded


I have a div.bodywhich contains an img amongst a couple more elements.

I need to get the height of div.body after img has been loaded.

I'm currently using the following to measure:

var $body = $("div.body");
$body.find("img").ready(function(){
   var bodyHeight = $body.outerHeight();
});

This returns the correct height 90% of the time, however some times it is returning the height not including the height of the image.


For example, if the other elements in div.body sum up to 50px, and my image has a height of 150px, I need to get 200px, however sometimes this is returning just 50px.


Why is this? Shouldn't the .ready() function only be called after the image has loaded?

Should I be using a different method?

What is a 100% consistent way of running this code once the image is available?


Solution

  • .ready() runs when the entire page's DOM is loaded. You want .load().

    See the discussion section here for an implementation that works for dynamically added content.