Quick Tip: Display Elements Sequentially with jQuery
videos

Quick Tip: Display Elements Sequentially with jQuery

Tutorial Details

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.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://pippinspages.com Pippin

    Awesome! So simple . . .

  • http://matt-bridges.com/ Matt Bridges

    Fantastic as always, Jeff! Looking forward to integrating this into a future project.

  • http://rommelcastro.me Rommel Castro A

    nice tip, thanks for share

  • http://kodifica.com Massimo Lombardo

    Too much overhead! Combining the each() index with the delay() method makes it even simpler:

    $(“img”).hide().each(function (i) {
    var delayInterval = 100; // milliseconds
    $(this).delay(i * delayInterval).fadeIn();
    });

  • http://kodifica.com Massimo Lombardo

    Oh, BTW, I used images, you list items, but the same theory applies.

    • http://pixoliacreative.com/ Raymond Lopez

      Thanks dude!

  • anon

    Great, and when JS is disabled they are visible.

  • SFdude

    Hi Jeff,

    In Firefox 3.6.13 (latest),
    under Win XP-Pro SP3:

    the online DEMO shows the link:
    _Show Images_

    but…no images are shown at all.

    At the end of the DEMO,
    the link _Show Images_
    will move down, with a big blank area above (where the Images should have appeared sequentially).

    SFdude

  • http://www.decodize.com praveen vijayan

    Super cool..

  • http://posthope.com Paul

    Nice tip, however would be more functional if it also did not run the http request for each image till it was ready to display.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      True — I think we have an image preloader tut somewhere on the site.

  • Jhon

    Thanks for te clear explanation! appreciate it!

  • http://www.thomas-online.no Thomas Bensmann

    Why don’t you just do this?

    Just wondering

    $(‘li’).hide().each(function(i){
    $(this).delay(300*i).fadeIn(200);
    });

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      You could do that as well — but I wanted to show the recursive call method.

    • http://websitecenter.ca/ Iouri Goussev

      each is way better actually, because it is O(n) complexity while the one in screencast is O(n^2)

      • http://websitecenter.ca/ Iouri Goussev

        Javascript does not do tail-call optimization, so it will create a huge stack, and then unwind it. Use $.each().

  • http://www.umbraprojekt.pl/ mingos

    Ooooh, a recursive callback on the fade, that’s pretty smart! Thanks, Jeffrey, nice one!

  • http://www.atomicrobotdesign.com Mike

    I can see this being really useful.

  • http://pixelcoder.co.uk Jeffrey

    Jeffrey, thanks for the tip. Your understanding of operators (++i), logic, client and server side always amazes me.

    Full of useful information and techniques.

    Many thanks and best of luck for your new site.

  • http://shaneparkerphoto.com Shane Parker

    Jeffrey, when I click on the demo, I first see all the images loaded and then they’re hidden. Is there an easy solution to keep them from loading in the first place?

  • http://www.dazydude.net Rik de Vos

    No next chapter of “Convert a Warm, Cheerful Web Design to HTML and CSS”, but instead a quick-tip…

    I can live with that :)

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Rik – Next chapter is coming in an hour. :)

  • http://www.daniel-petrie.com Daniel Petrie

    Wouldn’t you need to put an if statement inside recursive function to check whether you faded in all the objects or not? Otherwise that loop will be running non-stop in the background after all the images are faded in right?

    • http://www.daniel-petrie.com Daniel Petrie

      oh nm, didn’t see the comment in the code section, you can delete this :/

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Yep — it won’t run beyond the number of list items in the collection.

  • chichibek

    wow, gracias seguro me sirve, excelente trabajo Jeffry

  • Christian

    Nice idea, but shouldn’t be used – it’s not as readable as it could be. The fact that Daniel Petrie needed to read the comment to understand it, is reason enough to avoid this code.
    You have to think about it before you understand that it stops because the callback will not be called. If it’s written using the each() function or using a loop, you don’t need to think about it. Recursions aren’t thought to be used for this kind of work, instead loops are.

  • http://zecel.com Shishant Todi

    Good work, keep it up…

  • jeff

    Very Cool. Is there a way to get the same effect with out clicking ? ( like when i load the page ) tks
    jeff

  • Tobias Jurga

    What should I do to make it “backwards” like “hide images” on 2nd click?

    so when i click show images the first time it will display the images, but when i hit the button for the 2nd time it hides them again? is there any possibiliity to make that? I’m not really into javascript…
    here’s my actual code:

    (function() {
    var lis = $(‘ul’).hide();

    $(‘a’).click(function() {
    var i = 0;
    (function displayImages() {
    lis.eq(i++).slideDown(1500, displayImages);
    })();
    });
    $(‘a’).click(function() {
    var i = 0;
    (function hideImages() {
    lis.eq(i++).slideUp(1500, hideImages);
    })();
    });
    })();

    and yes it is for the whole ul, not for every li.
    now it appears and disappears again..

    thx in advance

  • http://nizzledev.com Ricardo Guillen

    Don’t you have to stop this event? or it’ll be calling `displayImages` over and over again? whe the funcion reaches a non-defined selector would it stop?
    thanx.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      No – it automatically stops.

  • http://alessio.no.de alessio
  • http://www.chris-alix.com Pablinho

    Very neat, I can see the use of this for loading gallery thumbnails..

  • http://www.daxhansen.com Dax

    Very cool! Thank you.

  • http://www.matbaa-tr.com matbaa

    Thanks to this course open in a new image I used in my project thank you very much, this interactive

  • http://www.kase-tr.com kaşe

    worked for me a very informative article explaining issues in this element has been good luck thank you very much

  • regie

    how about the reverse of it. .something like each would fadeOut one by one. .

  • http://javarevisited.blogspot.fr Java Geek

    fantastic tip. I am big fan on JQuery, it helps me to take full advantage of JS and love to learn this kind of simple tips. cheers

  • http://www.facebook.com/mittul.chauhan Mittul Chauhan

    great work again from you and as always .. so many blesses from me and from india. May you go on and on and on …

  • Gary

    Fantastic tutorial.

    I’ve just combined this method with your iNettuts widget tutorial. It gives a really nice feel when the user logs into their site.