faressoft
faressoft

Reputation: 19651

How can i know if all <img> loaded in div using jQuery

How can i know if all loaded in div using jQuery

i want to do this after load all img in #slider div

var imgHeight = $("#slider img").height();
alert(imgHeight);

Upvotes: 0

Views: 3116

Answers (2)

Yi Jiang
Yi Jiang

Reputation: 50105

You can use the load event

$('#slider img').load(function(){
    var imgHeight = $(this).height();
    alert(imgHeight);
});

if there are more than one image, and you only want to obtain the height after they have all loaded, try this code

var img = $('#slider img');
var length = img.length;

img.load(function(){
    length--;

    if(length === 0){
        alert("All images loaded");
    };
});

Well, I've tested the code, and it appears that the problem hasn't got anything to do with the code. When loading the page with the images already in the cache, this is what I get:

alt text

Strangely, this does not occur when I force the browser not to use the cache.

Upvotes: 9

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

Try this:

  • Attach an onload event listener to each image in the slider.
  • In the listener:
    • Give the current image a custom attribute to mark it is 'ready'.
    • Check if all images are ready. If so, do your thing (i.e. alert(imageHeight))

untested:

(function(){
  var slider=document.getElementById('slider'),
      images=slider.getElementsByTagName('img'), image, i=-1;

  while (image=images[i]) {
    image.onload=function(){
      this['data-ready']=true;
      var image, i=-1;
      while (image=images[i]) if (!image['data-ready']) return;
      // all images are ready; do your thing here
      // ...
    }
  }
}());

Upvotes: 0

Related Questions