3

I use a function to dynamically load images to a div via ajax call. I need to show a loading gif image when the image starts loading and hide when all the images finish loading. My primary task is to know when all the images have finished loading.

This is my code

 $('img').on('load', function ()
 {
alert("image loaded: "+this.src);
 });

But, this alert keeps on calling for each image.

Remember that the images are loaded via ajax call after the page is loaded.

1
  • For debugging purposes use Console.log("") rather than alert. This is so you don't have to manually go through every alert
    – Bobby
    May 12, 2014 at 14:49

2 Answers 2

1

Do it this way,

function loadAllImagesFromArray(images){
     for(i = 0 ; i < images.length; i++){
        var imageUrl = images[i];
        // closure to make sure that the value of i is preserved inside the context
        (function(i){
           $.ajax({
             url: imageUrl,
           }).done(function(image) {
             if(i == images.length - 1)
              alert("Image loaded");
           });
        }(i));
      }
    }
3
  • I dont have all the images in an array. They are contained somewhere in the div with class of the img as "parent"
    – Mirza
    May 12, 2014 at 15:55
  • 1
    Well, I showed you the typical way to handle the asynchronous request. You could take this as an example and implement this to suit your need.
    – Sandeep
    May 12, 2014 at 16:09
  • Good ans, im modifying it to suit my need here.
    – Mirza
    May 12, 2014 at 18:15
1

You could count all of the $('img') you have on the screen and increment a variable every time a image has loaded. Once the count is the same as the number of images call your alert.

1
  • 1
    As bobby said, I will use a counter and I will decrease that each time that image is load. Then trigger the event when the counter is 0.
    – fray88
    May 12, 2014 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.