How to Run a Function After jQuery fadeOut
When working with jQuery animations like fadeOut(),
JavaScript continues executing subsequent lines of code immediately
because animations are asynchronous. To ensure a specific function runs
only after the fadeOut() transition has completely
finished, you must use either jQuery's built-in completion callback
parameter or the .promise() method. This guide explains
both approaches clearly, showing you how to sequence your code properly
and avoid common execution timing mistakes.
Method 1: Using the Callback Parameter (Recommended)
The simplest and most common way to run a function after
fadeOut() finishes is by passing a callback function as an
argument. The fadeOut() method accepts a duration followed
by a completion callback function.
$("#myElement").fadeOut(400, function() {
// This code runs only after the fadeOut animation is completely finished
console.log("The element has finished fading out.");
doNextAction();
});You can also pass a pre-defined named function directly:
function onFadeComplete() {
console.log("Animation complete.");
}
// Pass the function reference (without parentheses)
$("#myElement").fadeOut("slow", onFadeComplete);Method 2:
Using .promise().done() for Multiple Elements
If your selector matches multiple elements (for example, a class like
.cards), a standard callback will trigger once for
every single matched element. If you want a function to run
only once after all selected elements have finished fading out,
use the .promise() method combined with
.done().
$(".cards").fadeOut(500).promise().done(function() {
// This runs exactly once, after all .cards have finished fading
console.log("All cards are hidden.");
});Common Pitfall: Invoking the Function Immediately
A frequent mistake is adding parentheses to the callback function
inside fadeOut(). Doing this executes the function
immediately when the line is read, rather than waiting for the animation
to finish:
- Incorrect:
$("#myElement").fadeOut(400, myFunction());(Executes instantly) - Correct:
$("#myElement").fadeOut(400, myFunction);(Executes upon completion) - Correct:
$("#myElement").fadeOut(400, function() { myFunction(); });(Executes upon completion)