Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback of .animate() gets called twice jquery

Since I added some scrollTop-animation, some parts of my callback get called twice:

$('html, body').animate({scrollTop: '0px'}, 300,function() {     $('#content').load(window.location.href, postdata, function() {                          $('#step2').addClass('stepactive').hide().fadeIn(700, function() {             $('#content').show('slide',800);                             });     }); }); 

It only seems to repeat the .show(), at least I don't have the impression that the load() or the .fadeIn() get called a second time too. The .show() gets repeated as soon as it has finished for the first time. Setting the scrollTop animation-speed to 0 didn't help by the way!

I assume it has something to do with the animation-queue, but I can't figure out how to find a workaround and especially why this is happening.

like image 330
Anonymous Avatar asked Jan 09 '12 15:01

Anonymous


1 Answers

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.

like image 90
Kevin B Avatar answered Oct 08 '22 18:10

Kevin B