Artem Svirskyi
Artem Svirskyi

Reputation: 7849

jquery animate multiple elements with delay

I want to animate multiple elements with jQuery one after another, so

$("div").each(function(i){
    $(this).delay(i*1000).animate({left: "+=200"}, {duration: 3000});
});

http://jsfiddle.net/eP2C3/1/
And now I need them to fadeOut while moving. If duration is 3000ms I add 2500ms delay and fade it out in 500ms.

$("div").each(function(i){
    $(this).animate({left: "+=200"}, {duration: 3000, queue: false})
            .delay(2500)
            .animate({opacity: 0}, {duration: 500});
});

http://jsfiddle.net/eP2C3/
But if I combine it with previous example they would animate simultaneously. And delay only opacity animation.

$("div").each(function(i){
    $(this).delay(i*1000).animate({left: "+=200"}, {duration: 3000, queue: false})
            .delay(2500)
            .animate({opacity: 0}, {duration: 500});
});

http://jsfiddle.net/eP2C3/2/

Upvotes: 0

Views: 4996

Answers (2)

Radu Bompa
Radu Bompa

Reputation: 1634

Ok, the problem was slightly more complicated than I thought, but I think i have an answer now. Unfortunately you cannot use jQuery animate function, because it is queueing your animations and you cannot apply two animations with different settings at the same time (at least to my knowledge). So you can try something like this:

$('div').each(function (i) {
    var $this = $(this);
    $this.delay(i * 1000).animate(
        {
            left: '+=200'
        },
        {
            duration: 3000,
            start: function () {
                setTimeout(function () {
                    setInterval(function () {
                        $this.css({opacity: '-=0.04'});
                    }, 30);
                }, 2500);
            }
        }
    );
});

The setInterval function is used to create the animation effect. I hope this helps. JSFiddle here: http://jsfiddle.net/eP2C3/44/

Upvotes: 1

Mark S
Mark S

Reputation: 3799

You should remove the queue: false. The delay() will be ignored if you specify the animation not to be queued because delay is a callback that is also added to the queue.

Here I've updated your jsfiddle: http://jsfiddle.net/eP2C3/10/


Update:

If you need opacity animation to start after 2500ms from the start left animation then queue: false should be applied to do this. However .delay(i*1000) will be ignored but a good workaround is to use setTimeout() to begin the animation:

$("div").each(function(i){
    var div = $(this);
    setTimeout(function(){
    div.animate({left: "+=200"}, {duration: 3000, queue: false})
            .delay(2500).animate({opacity: 0}, {duration: 500});
    },i*1000);
});

See this updated jsfiddle: http://jsfiddle.net/eP2C3/36/

Upvotes: 4

Related Questions