Advertisement
  1. Code
  2. Web Development

Quick Tip: Display Elements Sequentially with jQuery

Scroll to top
Read Time: 1 min

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.

1
2
// Wrapping, self invoking function prevents globals

3
(function() {
4
   // Hide the elements initially

5
   var lis = $('li').hide();
6
		
7
   // When some anchor tag is clicked. (Being super generic here)		

8
   $('a').click(function() {
9
      var i = 0;
10
      
11
      // FadeIn each list item over 200 ms, and,

12
      // when finished, recursively call displayImages.

13
      // When eq(i) refers to an element that does not exist,

14
      // jQuery will return an empty object, and not continue

15
      // to fadeIn.

16
      (function displayImages() {
17
         lis.eq(i++).fadeIn(200, displayImages);
18
      })();
19
   });	
20
})();

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.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.