Callback of .animate() gets called twice jquery

To get a single callback for the completion of multiple element animations, use deferred objects.

$(".myClass").animate({
  marginLeft: "30em"
}).promise().done(function(){
  alert("Done animating");
});

When you call .animate on a collection, each element in the collection is animated individually. When each one is done, the callback is called. This means if you animate eight elements, you’ll get eight callbacks. The .promise().done(...) solution instead gives you a single callback when all animations on those eight elements are complete. This does have a side-effect in that if there are any other animations occurring on any of those eight elements the callback won’t occur until those animations are done as well.

See the jQuery API for detailed description of the Promise and Deferred Objects.

Leave a Comment