Callback Functions for Effects and Animations

Get introduced to callback functions for jQuery effects and animations and explore their use cases.

How to wait for an effect to conclude

Often, we need to perform a specific task after a given effect is concluded, like deleting an element after the fade-out effect is completed. Since the code is executed line-by-line, you might think that if we place a task after the effect in code, it will execute that task after the effect is concluded.

However, that is not the case. Consider the example below. In the “Fade Out” button event handler, we fade out the div element using the fadeOut() effect in line 3. Then in line 4, we generate an alert box with text “Task to be performed after the fade-out effect!”

Run the code below. In the web page output, click on the “Fade Out” button element. You will see that the alert pops up before the fade-out effect completes.

So, what happened here?

In jQuery, once an effect or animation is initiated, it continues in the background, while the jQuery execution is not interrupted, and the execution moves to the next line to generate the alert. This is due to the asynchronous nature of JavaScript.

Solution: Callback functions

Callback functions come to our rescue when addressing the problem mentioned above.

A callback function, for a given effect, is executed after the completion of the effect.

Each effect and animation in jQuery takes optional parameters of the speed and the callback function. The syntax is as follows:

// for effects
$("selector").effect("speed", function(){
     // callback func: code executes after effect concludes
}); 
// for animations
$("selector").animate({css__parameters},"speed", function(){
     // callback func: code executes after animation concludes
}); 

The code within the callback function executes after the effect or animation finishes its execution. For more details on JavaScript’s callback functions, check out this page.

Example

Consider that same example as above. Now, we will place the alert inside the callback function of the fade-out effect, shown below:

Run the code below. In the web page output, click on the “Fade Out” button element. Notice now that the alert pops up after the fade-out effect completes.