Question

I am working with a div that has any number of img elements inside it. Right now, each img has the following CSS:

#content > img {
display: none;
position: absolute;
top: 0px;
left: 0px;
}

And the images can be cycled-through with a function that shows and hides them in turn. While each image is loading, however, I'd like to display a "loading..." image. I'd like to use JavaScript/jQuery to swap the source of each incomplete image for the "loading..." image while still permitting it to load. What's a lean and mean way to do this?

Was it helpful?

Solution

$(function(){
   $('<img>').attr('src','loading.gif'); // preload the "loading" image.

   $('#content > img').each(function(){
       var original = this.src;
       var $this = $(this);
       $this.attr('src','loading.gif'); // swap to loading image.
       $('<img>').attr('src',original)// pre-load original.
              .load(function(){
                 $this.attr('src',original); // swap it back when pre-load is done. 
              });
   })
});

crazy example

OTHER TIPS

There's an imagesLoaded plugin that can be found here: http://gist.github.com/268257

Just show the loading image, bind to the imagesLoaded event and when it's triggered, hide the loading image.

UPDATE:

Actually, jQuery has built in methods to detect loading now: http://api.jquery.com/load-event/

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