Question

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?

Was it helpful?

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.

OTHER TIPS

Per jQuery's documentation, there are a number of caveats for using the load event with images.

Take a look here:

jQuery event for images loaded

and here:

https://github.com/desandro/imagesloaded

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top