In my learning I have always learnt and understood callbacks in jQuery like this:
A callback function is executed after the current animation (effect) is finished.
[...] with animations, the next line of code can be run even though the animation is not finished. This can create errors. To prevent this, you can create a callback function. The callback function will not be called until after the animation is finished开发者_StackOverflow. Citation: www.w3schools.com[...]
and
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. Citation: www.jquery.com[...]
But my callback use doesn't work for some reason.
Look at the following code:
$(page).slideUp("slow", function() {
$('div#details').html(details);
$(page).slideDown("slow");
});
This should make the contentbox slide up and therefore disappear, then the content is changed to something new, and lastly the contentbox slides down (appears) again. I need these three steps to happen after one another in this order, but each step must only begin when the previous has finished. That is why I use a callback instead of just having this:
$(page).slideUp("slow");
$('div#details').html(details);
$(page).slideDown("slow");
Which will make everything happen at the same time.
My code works, and I can shift the page content at a click of a button. But the animations don't react as I expected from this. When the button is clicked, the content immediately disappears without any animated slideUp. The new content does then slideDown in a fine animation.
Click around the left sidemenu here, to see what happends.
I don't understand why there is no animated slideUp, but I suspect the callback doesn't act like I thought it would. It seems that the callback fires when the first animation starts, instead of waiting to fire until the animation has finished. Or maybe it's just the slideUp that doesn't work at all?
Can anyone explain to me, what I don't know and don't see in this extremely simple code including a callback?
You can use the delay function as a workaround.
$(page).slideUp(500);
$('div#details').html(details);
$(page).delay(500).slideDown(500);
Put the slideDown in the callback
$(page).slideUp("slow", function() {
$('div#details').html(details);
$(page).slideDown("slow");
});
Your previous code only updated the div #details upon completion of slideUp.
精彩评论