jQuery Callback
jQuery Callback
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. 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:
$(selector).slideToggle(duration, callback);
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.
Example
<script> $(document).ready(function(){ $("button").click(function(){ $("p").slideToggle("slow"); alert("The slide toggle effect has completed."); }); }); <script>
And, here's the modified version of the pevious 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.
Example
<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 the callback functions for the other jQuery effect methods, like show(), hide(), fadeIn(), fadeOut(), animate(), etc.
Example
<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 same alert message two times once per <h1> and <p> element, upon clicking the trigger button.