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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With