jQuery: sequential thumbnail loader

jQuery: sequential thumbnail loader

How to implement a sequential thumbnail loader with jQuery.

Loading and preloading thumbnails is a commonly requested task in jQuery. Loading thumbnails sequentially requires the use of a progressive timer which delays the execution of each fading effect for a given time span. The rest is pretty simple.

We have a series of thumbnails:


<div id="thumbs">
	<figure>
		<img src="1-thumb.jpg" alt=""/>
	</figure>
    
	<figure>
		<img src="2-thumb.jpg" alt=""/>
    </figure>
    <figure>
	    <img src="3-thumb.jpg" alt=""/>
    </figure>
    <figure>
	    <img src="4-thumb.jpg" alt=""/>
    </figure>
</div>

We need to show a spinner before displaying each thumbnail. I'm going to dynamically attach an animated GIF to each thumbnail block with jQuery. This kind of image must be initially hidden:


#thumbs .loader {
	display: none;
}

With jQuery the fading routine is as follow:

  1. Create an incremental time span (i) counter.
  2. Attach a spinner to each figure block.
  3. Loop through the thumbnails.
  4. Hide them.
  5. Create a delay with setTimeout() by incrementing the counter by 800 on each loop.
  6. Fade in the spinner with a speed equal to 1/4 of 800.
  7. Hide the spinner.
  8. Fade in the thumbnail.

Here's the jQuery code:


var preload = function() {

    var i = 0;

    $('figure', '#thumbs').each(function() {
        var $figure = $(this);
        var loader = '<img src="loading.gif" class="loader"/>';
        $figure.append(loader);
    });

    $('img', '#thumbs').not('img.loader').each(function() {
        var $img = $(this);
        var $loader = $img.next();
        $img.hide();

        setTimeout(function() {
            $loader.fadeIn(i / 4, function() {

                $(this).hide();
                $img.fadeIn(200);

            });
        }, i += 800);

    });

};

preload();​

You can see the demo on this page.