Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A non-nested animation sequence in jQuery?

I'm trying to create an animation sequence with jQuery where one animation starts after the previous one is done. But I just can't wrap my head around it. I've tried to make use of the jQuery.queue, but I don't think I can use that because it seems to have one individual queue for each element in the jQuery array.

I need something like:

$('li.some').each(function(){
    // Add to queue
    $(this).animate({ width: '+=100' }, 'fast', function(){
        // Remove from queue
        // Start next animation
    });
});

Is there a jQuery way to do this or do I have to write and handle my own queue manually?

like image 728
98374598347934875 Avatar asked Jul 26 '11 11:07

98374598347934875


1 Answers

You can make a custom .queue() to avoid the limitless nesting..

var q = $({});

function animToQueue(theQueue, selector, animationprops) {
    theQueue.queue(function(next) {
        $(selector).animate(animationprops, next);
    });
}

// usage
animToQueue(q, '#first', {width: '+=100'});
animToQueue(q, '#second', {height: '+=100'});
animToQueue(q, '#second', {width: '-=50'});
animToQueue(q, '#first', {height: '-=50'});

Demo at http://jsfiddle.net/gaby/qDbRm/2/


If, on the other hand, you want to perform the same animation for a multitude of elements one after the other then you can use their index to .delay() each element's animation for the duration of all the previous ones..

$('li.some').each(function(idx){
    var duration = 500; 
    $(this).delay(duration*idx).animate({ width: '+=100' }, duration);
});

Demo at http://jsfiddle.net/gaby/qDbRm/3/

like image 121
Gabriele Petrioli Avatar answered Sep 22 '22 23:09

Gabriele Petrioli