jQuery - SPLessons

jQuery Callback Functions

Home > Lesson > Chapter 14
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

jQuery Callback Functions

jQuery Callback Functions

shape Description

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.

shape Syntax

The syntax of callback function is
$(selector).hide(speed,callback);

Normal Execution without Callback Function

shape Example

In below example, the code will be executed without callback function. [html] <html> <head> <title>jQuery callback functions</title> </head> <body> <h1>Welcome to SPLessons</h1> <div> <p>click on this paragraph</p> </div> </body> </html> [/html] [javascript] $(document).ready(function() { $("p").click(function() { $(this).fadeOut(7000); alert("The paragraph is not fade out!!!"); }); }); [/javascript] Output:

shape More Info

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] <html> <head> <title>jQuery callback functions</title> </head> <body> <h1>Welcome to SPLessons</h1> <div> <p>click on this paragraph</p> </div> </body> </html> [/html] [javascript] $(document).ready(function() { $("p").click(function() { $(this).fadeOut(7000, function() { alert("The paragraph is faded out!!!"); }); }); }); [/javascript] Here the alert box appears after the completion of effect. Output:

Summary

shape Key Points

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