android.nick
android.nick

Reputation: 11215

Jquery: how to: when UL is shown, have first LI animate 'left' 20px, then to 0px, then have the second LI do that, then third, etc

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.

Upvotes: 0

Views: 810

Answers (2)

Ender
Ender

Reputation: 15221

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/

Upvotes: 3

treeface
treeface

Reputation: 13351

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.

Upvotes: 0

Related Questions