jQuery Callback


The callback functions


Line by line, JavaScript statements are executed. However, since jQuery effects take time to complete, the next line code can run while the previous effect is still active. jQuery includes a callback function for each impact method to prevent this from occurring.

A callback function is one that is called after the effect has finished. The callback function is passed as an argument to affect methods, and it is usually the method's last argument. The basic syntax of the jQuery slideToggle() impact method with a callback function, for example, is as follows:



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



Take a look at the example below, where the slideToggle() and alert() statements are next to each other. If you use this code, the message will appear as soon as you press the trigger button, without having to wait for the slide toggle effect to finish.



$(document).ready(function(){
  $("button").click(function(){
    $("p").slideToggle("slow");
    alert("Completed Successfully.");
  });
});

Live Demo!


Here's a modified version of the previous example, in which the alert() statement is contained inside a slideToggle() method callback feature. When you run this code, an alert message will appear after the slide toggle effect has finished.



$(document).ready(function(){
  $("button").click(function(){
    $("p").slideToggle("slow", function(){
      // Code to be executed
      // once effect is complete
      alert("Completed Successfully");
    });
  });
});

Live Demo!


Similarly, callback functions can be defined for other jQuery effect methods such as show(), hide(), fadeIn(), fadeOut(), animate(), and so on.



$(document).ready(function(){
  $("button").click(function(){
    $("h1, p").slideToggle("slow", function(){
      // Code to be executed
      // once effect is complete
      alert("Completed Successfully.");
    });
  });
});

Live Demo!


If you use the above example code, the same warning message will appear twice, once for each <h1> and <p> part, when you click the trigger button.