Roberto Barra
Roberto Barra

Reputation: 25

Animating in jquery: running a function after a group of animation finishes

I'm animating a group of divs that need to move together. Each div will follow a different path, and will move at same time, for the same period.

After this piece of the animation is over, I'd like to run some code to redraw some other stuff.

I'm using jquery for this. Here is a sample code of what I'm doing:

    // units is an array containing the divs encapsulated on $()
for (var i = 0; i < units.length; i++)
{
    var unit = units[i];
    var idUnit = unit.attr('id');

            // New coordinates
    var xNew = layout.x[idUnit];
    var yNew = layout.y[idUnit];

            // Actual coordinates
    var xAct = x(unit);
    var yAct = y(unit);

            // Animate!
    unit.animate(
            {left: xNew, top: yNew}, {
                duration: 1000, 
                easing: 'easeOutBack'
            }
    );
}

I could put the code I want to execute on the complete callback of one of the animate calls, but I'm looking for something like this:

queue.delay(1000).run(function(opts) {

   // Code goes here!

});

Is there a way to do this? Or should I rewrite my code to work with only one call to animate, and pass to it a custom stepper function?...

Upvotes: 1

Views: 108

Answers (2)

John S
John S

Reputation: 21482

If you have a jQuery variable named $units that holds all the elements to be animated, you can do this:

$units.each(function() {
    var $unit = $(this),
        id = $unit.attr('id');

    var xNew = layout.x[id],
        yNew = layout.y[id];

    $unit.animate({ left: xNew, top: yNew },
        { duration: 1000,  easing: 'easeOutBack' });
}).promise().done(function() {
    // This will execute after all the animations have finished.
});

Upvotes: 1

Lawrence Jones
Lawrence Jones

Reputation: 955

Use setTimeout(function () { /* do callback */ }, 1000) where 1000 is your duration of pause. Add this line just after the for loop.

Upvotes: 0

Related Questions