Effect Callbacks
Run code after an animation finishes using a callback function.
Syntax
$(selector).fadeOut(speed, function () { /* after */ });Animations take time. To run code after one completes, pass a callback function as the last argument.
$("#box").fadeOut(400, function () {
// runs only after the fade finishes
$(this).text("Done!").fadeIn(400);
});Without a callback, the next line runs immediately — before the animation ends.
Example
Loading editor…
Press Run to see the result.
When to use it
- A modal close animation uses a fadeOut callback to remove the element from the DOM only after it has fully faded.
- A multi-step wizard disables the Next button, runs a slide animation, and re-enables Next inside the completion callback.
- An AJAX spinner hides itself inside the success callback of a $.get() call to ensure the spinner never disappears early.
More examples
Remove element after fade completes
The callback passed to .fadeOut() runs only after the animation completes, ensuring .remove() is not called early.
<div id="alert" style="padding:12px;background:#f39c12;color:#fff;">Alert! Click to dismiss.</div>
<script>
$(function () {
$("#alert").click(function () {
$(this).fadeOut(500, function () {
$(this).remove();
});
});
});
</script>Chain sequential animations via callbacks
Nested callbacks guarantee the colour change happens only after fadeOut, and the resize only after fadeIn.
<div id="box" style="width:60px;height:60px;background:#9b59b6;"></div>
<button id="start">Start sequence</button>
<script>
$(function () {
$("#start").click(function () {
$("#box").fadeOut(400, function () {
$(this).css("background", "#2ecc71").fadeIn(400, function () {
$(this).animate({ width: "120px" }, 400);
});
});
});
});
</script>Re-enable button after animation
The button is disabled before the animation and re-enabled inside the final nested callback to prevent double-clicks.
<button id="next" >Next step</button>
<div id="step" style="padding:16px;background:#eef;">Step 1</div>
<script>
$(function () {
var step = 1;
$("#next").click(function () {
$(this).prop("disabled", true);
$("#step").slideUp(400, function () {
step++;
$(this).text("Step " + step).slideDown(400, function () {
$("#next").prop("disabled", false);
});
});
});
});
</script>
Discussion