Callbacks are functions passed as arguments to other functions and executed only after the first function completes. They are extremely useful in animations and asynchronous tasks.
In jQuery, many animation methods accept a callback function that executes once the animation completes.
// Hide an element, then execute callback after animation
function hideThenShow() {
$("#callbackBox").hide(1000, function() {
alert("Hide complete!");
$("#callbackBox").show(1000);
});
}
// Perform fade animation and run callback when fadeOut finishes
function fadeAndChangeColor() {
$("#fadeBox").fadeOut(800, function() {
$(this).css("background", "#ffe082");
$(this).text("Color changed! Now fading in...");
$(this).fadeIn(800);
});
}
You can nest callbacks within each other to create complex, multi-step sequences that fire exactly when you want them to.
// Nesting callbacks for a 3-step sequence
function runChainSequence() {
$("#chainBox").slideUp(500, function() {
// This runs after sliding up
$(this).css("border-color", "var(--danger)");
$(this).text("Sequence: Step 2 Complete!");
$(this).slideDown(500, function() {
// This runs after sliding back down
alert("All steps finished!");
});
});
}
Each animation waits until the previous one completes. The callback ensures that color changes and fade-in happen only after fade-out finishes.