jQuery Callback Functions – Ensuring Code Runs at the Right Time
In JavaScript, code is executed line by line, even if an effect (like hide() or fadeOut()) is still running. This can lead to unexpected behavior when the next statement depends on the animation being finished.
To solve this, jQuery provides callback functions — functions that are executed only after an effect has completed.
Syntax:
$(selector).hide(speed, callback);
The callback parameter is a function that runs after the hide() effect is fully completed.
Example With Callback:
In this example, the alert appears after the paragraph is completely hidden:
$("button").click(function() {
$("p").hide("slow", function() {
alert("The paragraph is now hidden");
});
});
Example Without Callback:
Here, the alert box shows up immediately, before the paragraph finishes hiding:
$("button").click(function() {
$("p").hide(1000);
alert("The paragraph is now hidden");
});
Using callback functions helps maintain proper flow and ensures that actions dependent on animations happen at the right time.