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.
animate
calls its callback once for each element in the set you callanimate
on:Since you're animating two elements (the
html
element, and thebody
element), you're getting two callbacks. (For anyone wondering why the OP is animating two elements, it's because the animation works onbody
on some browsers but onhtml
on other browsers.)To get a single callback when the animation is complete, the
animate
docs point you at using thepromise
method to get a promise for the animation queue, then usingthen
to queue the callback:(Note: Kevin B pointed this out in his answer when the question was first asked. I didn't until four years later when I noticed it was missing, added it, and...then saw Kevin's answer. Please give his answer the love it deserves. I figured as this is the accepted answer, I should leave it in.)
Here's an example showing both the individual element callbacks, and the overall completion callback:
To get a single callback for the completion of multiple element animations, use deferred objects.
See the jQuery API for detailed description of the Promise and Deferred Objects.