JavaScript statements are executed line by line. However, with effects, the next line of code can be run even if the effect is not finished. This can create errors. A **callback function** is executed only after the current effect is 100% finished.
If you have an alert right after a hide() method, the alert will pop up
**before** the hiding animation is done. This happens because JavaScript doesn't wait
for the animation to finish.
$("p").hide("slow");
alert("Finished!");
The alert will show up while the paragraph is still visible and fading.
$("p").hide("slow", function() {
alert("Finished!");
});
The alert will only appear after the paragraph is completely hidden.
A callback function is passed as the last argument to an effect method.
$(selector).hide(speed, callback);
You might want to remove an element from the DOM only after it has finished fading out to avoid a "jumping" UI.
$("button").click(function() {
$("#message").fadeOut("slow", function() {
// This code runs only AFTER fadeOut is complete
$(this).remove();
});
});
If your selector matches multiple elements (e.g., $("p")), the callback
function will be executed **once for each** hidden element. If you have 5 paragraphs,
a callback alert will pop up 5 times!
// Warning: This will alert once per paragraph!
$("p").hide("slow", function() {
alert("One paragraph hidden");
});
.promise().done() method. (Stay tuned for advanced sections!)
$(this) refers to the
element being animated.