In this tutorial you will learn how to use jquery callback function for the jQuery effect.
jQuery Callback Functions
JavaScript statements are executed line by line. But, since jQuery effect takes some time to finish the next line code may execute while the previous effect is still running. To prevent this from happening jQuery provides a callback function for each effect method i.e. jQuery callback function.
A callback function is a function that is executed once the effect is complete. The callback function is passed as an argument to the effect methods and they typically appear as the last argument of the method. For example, the basic syntax of the jQuery slideToggle()
effect method with a callback function can be given with:
Example
Consider the following example in which we’ve placed the slideToggle()
and alert()
statements next to each other. If you try this code the alert will be displayed immediately once you click the trigger button without waiting for slide toggle effect to complete.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example of jQuery Effect Method without Callback Function</title> <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <style type="text/css"> p{ background:yellow; font-size: 24px; padding:20px; } </style> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("p").slideToggle("slow"); alert("The slide toggle effect has completed."); }); }); </script> </head> <body> <p>This is paragraph.</p> <button type="button">Click me</button> </body> </html>
And, here’s the modified version of the pevious jquery callback example in which we’ve 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 type="text/javascript"> $(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 the callback functions for the other jQuery effect methods, likeshow()
, hide()
, fadeIn()
, fadeOut()
, animate()
, etc.
Note:If the effect method is applied to multiple elements, then the callback function is executed once for each selected element, not once for all.
<script type="text/javascript"> $(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>
jQuery Callback Functions
In this tutorial you learn how to use Callback Functions in jQuery. If you have any other question in your mind relating this topic, you can leave your question at our Forum Section.