jQuery Callback
JavaScript runs code without waiting for the previous line to finish, so an animation and the statement after it can start at the same time. A callback function is code you pass to an effect that jQuery runs only after that effect has completely finished, which lets you keep your animations in the right order.
Why Callbacks Matter
Effects like hide(), fadeOut(), and slideUp() take time to play. Because JavaScript does not pause for them, any code written on the next line runs immediately, while the animation is still in progress. This can lead to bugs where you act on an element before its effect has finished.
Without a callback (runs too early)
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button>Hide</button>
<p>This is a paragraph.</p>
<script>
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden"); // fires before hiding finishes
});
</script>
</body>
</html>Adding a Callback Function
A callback is simply a function passed as the last argument to the effect method. jQuery stores it and executes it once the effect on that element has ended, guaranteeing the correct order.
With a callback (runs at the right time)
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button>Hide</button>
<p>This is a paragraph.</p>
<script>
$("button").click(function(){
$("p").hide(1000, function(){
alert("The paragraph is now hidden"); // fires after hiding completes
});
});
</script>
</body>
</html>Sequencing Effects with Callbacks
Callbacks are a natural way to run one effect after another. By starting the next animation inside the callback of the first, you create a reliable chain where each step waits for the one before it.
Running effects in sequence
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="go">Go</button>
<div id="box" style="width:100px; height:100px; background-color:lightblue;"></div>
<script>
$("#go").click(function(){
$("#box").fadeOut(800, function(){
$(this).css("background", "orange").fadeIn(800);
});
});
</script>
</body>
</html>- A callback runs only after the effect on the element has fully finished.
- Inside the callback, the keyword this refers to the DOM element the effect ran on.
- Callbacks keep animations in order and prevent code from firing too early.
- If an effect matches several elements, the callback runs once for each element.
Exercise: jQuery Callback
When does a callback passed to .fadeOut() actually run?