tags:

views:

45

answers:

4

Each of the list items is "hidden" and each list can only be shown after the list item before it has been shown.

// HTML
<ul>
    <li id="list-1" class="list-item">
        <a href="#">List 1</a>
    </li>
    <li id="list-2" class="list-item">
        <a href="#">List 2</a>
    </li>
    <li id="list-3" class="list-item">
        <a href="#">List 3</a>
    </li>
</ul>



// CSS
ul li {
    overflow: hidden;
    position: relative;
}

ul li a {
    position: relative;
    top: -20px;
}


// jQuery
$('#list-1').animate({
    top: '0'
}, 500, function() {
    $('#list-2').animate({
        top: '0'
    }, 500, function() {
        $('#list-3').animate({
            top: '0'    
        }, 500)
    })  
})

The jQuery code above works if there is always going to be 3 list items, but how can that code be modified to accomodate any number of list items?

Thanks for any help!

+4  A: 

You could use the .list-item class for the selector, and inside an .each(), use .delay() to delay the animation by the index value of the current iteration multiplied by 500 milliseconds.

Try it out: http://jsfiddle.net/EFGCM/

$('ul > li.list-item').each(function( i ) {
    $('a',this).delay( i * 500 ).animate({ top: '0'}, 500);
});

The .delay() requires jQuery 1.4 or later.


EDIT: This would be a little more efficient.

http://jsfiddle.net/EFGCM/3/

$('ul > li.list-item > a').each(function(i) {
    $(this).delay(i * 500).animate({ top: '0'}, 500);
});
patrick dw
ohhh, thanks so much!
watduyuwan
@watduyuwan - You're welcome. :o)
patrick dw
Way more pretty than my implentation! nice.
Bart
A: 

Why don't you do it with display: none;?

That way you can use the selector $("ul li:hidden:first") to select the next hidden li. Not tested, but shouldn't work. :)

Edit: to do the animation you can use the jquery function slideToggle() or slideDown() instead of just show()

Thomas Clayson
A: 

A recursive function may be what you are after. Something like this:

function animateCascade(element){
    var element = $(element);

    if (element.length==0) return; // no more elements

    element.animate(
        {top: '0'},
        500,
        function(){
            animateCascade(element.next('.list-tem')); // get the next LI
        }
    );
}
animateIt($('#list-1')); // start at the beginning LI
Bart
A: 

Alternative solution

function slide($li) {
    if ($li.length == 0) return;
    $li.slideDown(500, function() {
        slide( $li.next(".list-item") );
    });
}

slide( $("ul li:hidden:first") );

example: http://jsfiddle.net/MXxkd/

Simen Echholt