Steve Taylor photo

Fading in images sequentially in jQuery

This took me ages to figure out. I don’t know why. Anyway, I was creating a gallery of thumbnail images, and I wanted each image to fade in sequentially. The next image would start fading in before the previous one’s jQuery fadeIn had completed, so I couldn’t really use a callback.

Of course, the solution is a plain JavaScript setTimeout. The tricky bit was that for some reason this kind of code didn’t work:

thumbTimer = setTimeout( loadThumbs(), 70 );

In the end I had to use this:

thumbTimer = setTimeout( function() { loadThumbs(); }, 70 );

Grooooaaaaannn… Well, here’s the full function:

function loadThumbs() {
		var thumbTimer;
		// Initialize / increment counter
		if ( typeof loadThumbs.counter == 'undefined' ) {
			loadThumbs.counter = 0;
		} else {
			loadThumbs.counter++;
		}
		if ( loadThumbs.counter < numThumbs ) {
			// Load and fade in a thumbnail
			$( "#thumbnails" ).append( '<div class="tn" id="tn-' + loadThumbs.counter + '"><a href="&#91;????&#93;" title="Click to see full size"><div class="thumbnail" style="display:none;width:86px;height:86px;overflow:hidden;background:url(&#91;????&#93;) no-repeat ' + ( 0 - ( loadThumbs.counter * 86 ) ) + 'px 0px" /></a></div>' );
			$( "#tn-" + loadThumbs.counter + " div.thumbnail" ).fadeIn( 500 );
			thumbTimer = setTimeout( function() { loadThumbs(); }, 70 );
		} else {
			// All thumbs loaded, add "glow" event
			$( ".tn a" ).mouseover( function() {
				$( this ).children( ".thumbnail" ).stop( true, true ).animate({
					opacity: 0.6
				}, 200, "swing", function() {
					$( this ).animate({
						opacity: 1
					}, 400 );
				});
			});
		}
	}
}

A few words of explanation:

  • This code isn’t “self-contained”! You can’t just drop it somewhere and have stuff happen. I’m posting it to convey as specific bit of syntax (described above), and give it a bit of context. You’ll need a bunch of other HTML and CSS to get this going, and it should be obvious what’s needed. If it’s not, please Google for a complete image gallery solution.
  • You’ll need to call loadThumbs once the page is loaded, of course.
  • You’ll also need to set numThumbs inline on the page somewhere. I’m working this out server-side and using PHP to write the JS. You could try something else if you want…
  • The code is designed to work with a pre-existing div with thumbnails as an ID on the page.
  • Replace instances of [????] with your URL structure to full-size images and thumbnails.
  • For various reasons, I’m working with one big image which has all the thumbnails in a strip. Each thumbnails is 86 x 86 pixels, and each thumbnail’s div includes it as a background image, its position shifted to show the right bit.
  • Tweak the fadeIn and setTimeout millisecond settings as necessary!
  • I’ve include a nice “glow” effect as a bonus. :)