Use of Callback functions in jQuery

Javascript statements will be executed in the  line by line.While using animation function, next line will be executed before completing the animation function. This might cause an error. In order to overcome this callback function is used.

Callback function is executed only after the completion of animation function.

SYNTAX:

$(selector).hide(speed,callback)

$(selector).show(speed,callback)

$(selector).toggle(speed,callback)

EXAMPLE:

With callback function


<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").toggle(1000,function(){
alert("Click Toggle button to view");
});
});
});
</script>
</head>
<body>
<button>Toggle</button>
<p>Welcome to Learnwebdevelopment.info</p>
</body>
</html>

EXPLANATION:

Here the callback function will be executed after the animation function

Without callback function


<html>
 <head>
 <script type="text/javascript" src="jquery.js"></script>
 <script type="text/javascript">
 $(document).ready(function(){
 $("button").click(function(){
 $("p").toggle(1000)
 alert("Click Toggle button to view");
 });
 });
 </script>
 </head>
 <body>
 <button>Toggle</button>
 <p>Welcome to Learnwebdevelopment.info</p>
 </body>
 </html>

EXPLANATION:

Here the alert message will be displayed before the completion of  an animation

Posted in jQuery Tagged with: