views:

25

answers:

2

When UL.chapters is 'slideDown', have the first 'chapters LI' animate the 'left' property to 20px, then animate back to 0px, then have the second LI do the same thing, then have the third, and so-on. with my code, they all animate directly after UL.chapters slides down, how do I make them do their animation 1 at a time, with the second not starting until the first has finished, etc.

$('h1').click(function() {
    $('UL.chapters').slideDown(500);
    $('.chapters LI').each(function() {
        $(this).animate({'left':'20px'});
        $(this).animate({'left':'0px'});
    });
});

code updated.

A: 

Have you noticed the 4th line of your code is $('chapters LI') instead of $('.chapters LI')?

Also you're repeating yourself here. Try this:

$('h1').click(function() {
    $('UL.chapters').slideDown(500);
    $('.chapters LI').each(function() {
        $(this).animate({'left':'20px'});
        $(this).animate({'left':'0px'});
    });
});

Also make sure that your LIs are set to position absolutely, or else your left animate will have issues.

treeface
I like your code more, it's nicer, but they all do it at the same time, but I'm trying to make the first LI animate, then when it's done animating, have the second LI animate, then when the second LI is done animating, have the third LI animate, and so-on down the list of LI's until the last one.
android.nick
+3  A: 

Try this:

$(function() {
    $('h1').click(function() {
        $('.chapters').slideDown(500, function() {
            doSlide($('.chapters li:first'));
        });
    });

});


function doSlide(current) {
    $(current).animate({
        'left': '20px'
    }, function() {
        $(current).animate({
            'left': '0px'
        }, function() {
            doSlide($(current).next('li'));
        });
    });
}

This calls the slide animation function on the first <li> and then in the callback for the animation that slides it back to the starting position, it calls the function on the next <li>.

Here's a demo of it in action: http://jsfiddle.net/CBNgR/

Ender
awesome! would you know how to start the second LI when the first one is halfway done with the animation? So when the first LI is starting to animate back from 20px to 0px, start the second LI right when it starts animating back?
android.nick
@android.nick - For that, try putting the doSlide($current).next('li')); call immediately after the call to animate back to the starting position, instead of in the callback for that animate call. Check it out: http://jsfiddle.net/CBNgR/1/
Ender