Advertisement
JavaScript & AJAX

Quick Tip: Display Elements Sequentially with jQuery

by

In this video quick tip, I'll teach you how to add a bit of flair to your page, by displaying a set of elements sequentially. While there are numerous ways to accomplish this task, today, we'll review one technique that uses recursive functions.

// Wrapping, self invoking function prevents globals
(function() {
   // Hide the elements initially
   var lis = $('li').hide();
		
   // When some anchor tag is clicked. (Being super generic here)		
   $('a').click(function() {
      var i = 0;
      
      // FadeIn each list item over 200 ms, and,
      // when finished, recursively call displayImages.
      // When eq(i) refers to an element that does not exist,
      // jQuery will return an empty object, and not continue
      // to fadeIn.
      (function displayImages() {
         lis.eq(i++).fadeIn(200, displayImages);
      })();
   });	
})();

Conclusion

What makes this usage effective is the fact that, when lis.eq(i) refers to an element that doesn't exist in the wrapped set, an empty jQuery object will be returned. When this happens, the subsequent methods in the chain (fadeIn) will never be called.

Related Posts