The Callback function executes after the current animation 100% is complete.
Problems with JQuery animations
Many jQuery functions involve animations. These functions may use speed or duration as an optional parameter.
Example: $ ("P"). Hide ("slow")
the speed or duration parameter can set many different values, such as "slow", "fast", "normal", or milliseconds.
Instance
1<! DOCTYPE html>234<script src= "/jquery/jquery-1.11.1.min.js" ></script>5<script type= "Text/javascript" >6$ (document). Ready (function(){7$ ("button"). Click (function(){8$ ("P"). Hide (1000);9 });Ten }); One</script> A -<body> -<button type= "button" > Hide </button> the<p> this is a paragraph. </p> -<p> this is another paragraph. </p> -</body> -View CodeView results:
Default: After click:
Because JavaScript statements (directives) are executed one-by-in-order, the statements after the animation may produce errors or page conflicts because the animation is not yet complete.
To avoid this situation, you can add the Callback function as a parameter.
JQuery Callback function
When animation 100% is complete, the Callback function is called.
A typical syntax:
$ (selector). Hide (speed,callback)
The callback parameter is a function that is executed after the hide operation is completed.
Error (no callback)
123<script type= "Text/javascript" src= "/jquery/jquery.js" ></script>4<script type= "Text/javascript" >5$ (document). Ready (function(){6$ ("button"). Click (function(){7$ ("P"). Hide (2000);8Alert ("The paragraph is now hidden");9 });Ten }); One</script> A -<body> -<button type= "button" >Hide</button> the<p>this is a paragraph with little content.</p> -</body> -View CodeCorrect (with callback)
123<script type= "Text/javascript" src= "/jquery/jquery.js" ></script>4<script type= "Text/javascript" >5$ (document). Ready (function(){6$ ("button"). Click (function(){7$ ("P"). Hide (1000,function(){8Alert ("The paragraph is now hidden");9 });Ten }); One }); A</script> - -<body> the<button type= "button" >Hide</button> -<p>this is a paragraph with little content.</p> -</body> -View Code
Conclusion: If you want to execute a statement after a function that involves animation, use the callback function.
JQuery Callback function