Callback and Chaining play an important role in jQuery coding when using animate / effect methods. In this article we will understand it with the help of a small example.
We know that chaining gives us a way to eliminate the use of temporary variables in programming. But here we will see another benefit with a Callback function.In short, a Callback function (in it we can write other Callback functions for insider animate / effect) is executed only after the completion of the current animation.We know that JavaScript is base on jQuery. So the code in jQuery will also excute in a line by line fashion. But it is not. The execution order of code in animation / effect methods get changed and it is not line by line. It means in animation, the next line of simple code is executed without waiting; the first one to complete. The solution of this problem is Callback & Chaining. Let's understand it with an example. Suppose we want our code to execute in the following order:
$("div").slideDown("normal", function() { alert("slide Down"); });
$("div").css("background-color", "blue"); alert(" Background restored");});Again surprise !!!
This time the order of execution is as:
Background color is changed to Red
Background color is changed to blue
Alert message 'Background restored'
Animation is done & animation's callback function (alert message-'animation done')
SlideUp is done & its Callback function (alert message -'slideUp done')
SlideDown is done & its Callback function (alert message - 'slideDown done')
Why?Actually we have just controlled our alert messages (of animate(), slideUp(), and slideDown() ) and at this time alert messages are coming only after the completion of animation/effect. But still it is not what we want as other lines like .css() are executing first and then the animations follow.So, what else is wrong?As I said that Callback function is executed after the completion of the current animation/effect. We need to place our code inside the Callback function and it would solve our problem. Note the Chaining functionality of jQuery. $(" :button").click(function(){ $("div").css("background-color","red"); $("div").animate({"opacity" :0.5},"fast","linear", function(){ alert("animation done"); $("div").slideUp("normal",function(){ alert("slide Up"); $("div").slideDown("normal",function(){ alert("slide Down"); $("div").css("background-color","blue"); alert(" Background restored"); } ); } ); }); }); });Cheers!!!At this time it is working fine.
Pro WPF: Windows Presentation Foundation in .NET 3.0