jQuery Callback

jQuery Callback Functions

JavaScript statements are executed line by line. However, since jQuery effects take time to complete, the next line of code may execute while the previous effect is still running. To prevent this, jQuery provides a callback function for each effect method.

A callback function is a function that executes once the effect is complete. It is passed as an argument to the effect methods and typically appears as the last argument of the method. For example, the basic syntax of the jQuery slideToggle() effect method with a callback function is as follows:

$(selector).slideToggle(duration, callback);

Consider the following example, where we have placed the slideToggle() and alert() statements sequentially. If you try this code, the alert will be displayed immediately after clicking the trigger button, without waiting for the slideToggle() effect to complete.

<script>
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle("slow");
alert("The slide toggle effect has completed.");
});   
});
</script>

Here's a modified version of the previous example, where we have placed the alert() statement inside a callback function for the slideToggle() method. If you try this code, the alert message will be displayed once the slide toggle effect has completed.

<script>
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle("slow", function(){
// Code to be executed once effect is complete
alert("The slide toggle effect has completed.");
});
});   
});
</script>

Similarly, you can define callback functions for other jQuery effect methods such as show(), hide(), fadeIn(), fadeOut(), animate(), etc.

Note: If an effect method is applied to multiple elements, the callback function is executed once for each selected element, not once for all of them collectively.

<script>
$(document).ready(function(){
$("button").click(function(){
$("h1, p").slideToggle("slow", function(){
// Code to be executed once effect is complete
alert("The slide toggle effect has completed.");
});
});   
});
</script>

If you try the above example code, it will display the alert message twice: once for each <h1> and <p> element, upon clicking the trigger button.