views:

35

answers:

2

I have the following list:

<div id="test">test</div>

<ul>
    <li>foo</li>
    <li>bar</li>
    <li>sta</li>
    <li>cko</li>
</ul>

and the following jQuery code:

$(document).ready(function() {
    $('li').each(function(index) {
        $('#test').text($(this).text());
        $('#test').show("drop", { direction: "down" }, 500, function() {
            $("#test").delay(1000).hide("puff", {}, 100);
        });
    });  
 });

Logically, this should change the contents of the div test to foo, apply the drop and puff effect, change contents to bar, apply the effect, and so on. But when you run it, the entire .each loop finishes up before the effects are started, so the last element cko shows up first and gets animated 4 times.

How can i make each item get the effect and then move on to the next one?

+2  A: 

You need to add the first function on the queue as well if you want it to happen in the order of the queue, (using .queue()), like this:

$(function() {
    $('li').each(function(index) {
        var li = $(this);
        $('#test').queue(function(n) {
            $(this).text(li.text());            //set the text
            n();                                //call next function in the queue
        }).show("drop", { direction: "down" }, 500, function() {
            $(this).delay(1000).hide("puff", {}, 100);
        });
    });  
 });​

You can give it a try here. This queues the text setting to happen in sequence with the animations, which seems to be what you're after. Calling the function passed to your queue callback is important, as it's what advances the queue, firing the animation that follows in this case.

The .delay() will have a weird effect the way you have it as well, if you want it on the queue, do it like this:

$(function() {
    $('li').each(function(index) {
        var li = $(this);
        $('#test').queue(function(n) {
            $(this).text(li.text());
            n();
        }).show("drop", { direction: "down" }, 500)
          .delay(1000).hide("puff", {}, 100);
    });  
 });​

You can try it here, this will actually pause a second for each element before moving on.

Nick Craver
This almost works, but I need the puff animation to immediately follow the drop animation. Right now, all items slide up one by one and get puffed out together at the end. Let's fiddle with it on the link you gave...
aalaap
A: 

Not tested, but I think you can try:

$(document).ready(function() {
    animateItem($('li'), 0);
});

function animateItem(li, i) {
    if (li.length > i) {
        $('#test').text(li.eq(i).text());
        $('#test').show("drop", { direction: "down" }, 500, function() {
            $("#test").delay(1000).hide("puff", {}, 100, function() { 
                animateItem(li, i++);
            });
        });
    }
 }
tanathos