1

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?

Curtis
  • 101,612
  • 66
  • 270
  • 352

2 Answers2

3

.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.

Steffan Donal
  • 2,244
  • 4
  • 24
  • 47
  • My understanding is that `load` will only run if the image isn't already cached? – Curtis Nov 21 '12 at 09:21
  • My experience has been that it will execute when all content in the container you hook it onto is ready. It works fine on my website. – Steffan Donal Nov 21 '12 at 09:22
  • And that would be because my usage on `.load()` is only required once - The image isn't 'live' in the cache yet, as it needs to be fetched from disk. If you only need the `.load()` event while the page is loading, then this should work just fine. If you're using it on dynamically added content, then no, it won't work. – Steffan Donal Nov 21 '12 at 09:25
  • I've just changed `ready` to `load`, and the first time I loaded the page it worked fine. The second time, it didn't run the event (as the image is stored in cache). – Curtis Nov 21 '12 at 09:29
  • 1
    Do the same calculation in `$(window).load()` - This is run even when the images are cached, but be aware that it won't run until _everything_ is loaded. – Steffan Donal Nov 21 '12 at 09:32
0

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

Community
  • 1
  • 1
Richard
  • 21,728
  • 13
  • 62
  • 101