1

I have 40 images with the class .myImage with the css:

.myImage{
    position:absolute;
}

in jQuery I'm doing:

$('.myImage').each(function(){
    alert($(this).height());
});

I have the good height for something like the first 15 images, but then the alert is 0 until the very last image. And I'm quite sure that every image are displayed because with an other jQuery script I'm giving to each of them a position and they are all displayed.

How come after 15 images the alert is 0?

user2461031
  • 513
  • 2
  • 7
  • 17
  • 5
    If the image isn't loaded yet, how do you expect jquery (or the javascript engine) to obtain the height? – Kevin B Dec 12 '13 at 18:58

2 Answers2

6

Wait for all the images to load. The DOM will be ready, but the images won't have loaded. Use the window.load event instead of jQuery's document.ready

window.load = function(){
 $('.myImage').each(function(){
  alert($(this).height());
 });
};
Travis J
  • 81,153
  • 41
  • 202
  • 273
1

Or wait only for specific images to load

$(document).ready(function(){
  var images = $('.myImage');

  images.one('load', function (){
    images.each(function(){
      alert($(this).height());
    })
  }).each(function() {
      if(this.complete) $(this).load();
    });
});
Alex Vauch
  • 191
  • 1
  • 6
  • Note however this won't work consistently after the first page load due to cross-browser differences in how the load event is triggered on cached images. (not to mention the handler will trigger when each one loads, not when they are all loaded.) – Kevin B Dec 12 '13 at 19:26