Saturday 19 May 2012

JQuery animation: execute callback only once when all completed

Problem:

When using the animate function after selecting more than one item, my callback function is executed as many times as there are items. How do I get the callback function to execute only once when the entire animation is done?

Problem Example:

If, for example, you have five items with the class 'do-something', and you try the following code:

var ctr = 0;
var selected = $(".do-something");

var mycallback = function(){
  ctr++;
  alert(ctr);
}

selected.animate({
  // ... your animation stuff ...
}, 200, mycallback);

Rather than the hoped for single alert with the number 1, you'll receive five alerts with the numbers 1 through 5.

Solution:

As of JQuery version 1.6 you can use the promise() and done() functions to fire off your callback once after all the animations are completed.

For example, again if you have five items with the class 'do-something' the following code should now produce a single alert with the number 1:

var ctr = 0;
var selected = $(".do-something");

var mycallback = function(){
  ctr++;
  alert(ctr);
}

selected.animate({
  // ... your animation stuff ...
}, 200);

selected.promise().done(mycallback);

Other notes:

This was tested to work using JQuery 1.7.2 and Firefox 12.0.

References:

No comments:

Post a Comment