1

I have a list that has indexed classes - what would be the best way to show these one at a time upon fadeIn of the container div?

Jeff Voss
  • 3,637
  • 8
  • 46
  • 71

2 Answers2

7

Give them a common class, and do the fadeIn()[docs] in a loop using the each()[docs] method while delaying each one with the delay()[docs] method for a given duration multiplied by the index of the loop.

$('li.someClass').hide().each(function( i ) {
    $(this).delay( i * 400 ).fadeIn();
});

Each element will begin 400 milliseconds later than the previous.

Example: http://jsfiddle.net/4ANCj/

user113716
  • 318,772
  • 63
  • 451
  • 440
  • beautiful, thanks. is there any way to browse through jsfiddles? I'm very new to that – Jeff Voss Jul 04 '11 at 02:56
  • @WHITEB0X: Not sure exactly what you mean. Do you mean like a central repository of scripts? I'm not aware that jsFiddle has any sort of public showcase of scripts. I'm pretty sure you need direct links that others have posted. But who knows? Register an account and you may find more features. – user113716 Jul 04 '11 at 03:00
  • Nice solution. I've never trusted javascript timers to be 100% accurate though on unknown browsers, cpu's, etc. More of a callback fan myself. Props though I wouldn't have even thought of this method. – AlienWebguy Jul 04 '11 at 03:02
  • @AlienWebguy: Thanks. Yeah, the callback would ensure that one doesn't begin until the next is finished. One nice thing about this is that it lets you tweak the delay to allow a little overlap for a nice effect. Any lack of accuracy probably won't be noticed unless you have dozens of items, in which case things could get a little sloppy. Pretty sure they don't program pacemakers in JavaScript. :o) – user113716 Jul 04 '11 at 03:06
3
function fade_in_recursive(e,duration,callback)
{
    $(e).fadeIn(duration,function()
    {
        if($(e).next().length == 0)
        {
            if(typeof(callback) == 'function')
            {
                callback();
            }
            return;
        }
        else
        {
            // Apply recursion for every sibling.
            fade_in_recursive($(e).next(),duration,callback);
        }
    });

} // End fade_in_recursive

$(function()
{
    fade_in_recursive($('ul li:first-child'),500);
});

http://jsfiddle.net/2s4L8/

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145