jQuery - SPLessons

Chapter 14

jQuery Callback Functions

jQuery Callback Functions

A callback function is that function which will be executed whenever effect is completely finished. As statements of JavaScript are executed line by line, normally the line after the effect code will be executed without effect is completed. jQuery Callback functions can be used to prevent the execution of code before completing the effect.

The syntax of callback function is

$(selector).hide(speed,callback);

Normal Execution without Callback Function

In below example, the code will be executed without callback function.


<html>
  <head>
   <title>jQuery callback functions</title>
  </head>

  <body>
   <h1>Welcome to SPLessons</h1>
   <div>
      <p>click on this paragraph</p>
   </div> 
  </body>

</html>


$(document).ready(function()
{
      $("p").click(function()
{
         $(this).fadeOut(7000);
           alert("The paragraph is not fade out!!!");
      });
   });

Output:

When clicked on the paragraph, the alert box appears immediately even without the completion of effect. Once when clicked on the OK in the alert box,the effect can be seen completely. To avoid this delay, add a callback function. Modify the section like this:

<html>
<head>
   <title>jQuery callback functions</title>
</head>

 <body>
 
   <h1>Welcome to SPLessons</h1>
   <div>
      <p>click on this paragraph</p>
   </div>
   
   
  </body>
</html>

$(document).ready(function()
{
   $("p").click(function()
{
     $(this).fadeOut(7000, function()
{
        alert("The paragraph is faded out!!!");
});
});
});

Here the alert box appears after the completion of effect.

Output:

Summary

  • Callback function executes only after the completion of jQuery effect by setting time.