xoops forums

kaotik

Just can't stay away
Posted on: 2010/5/6 14:51
kaotik
kaotik (Show more)
Just can't stay away
Posts: 861
Since: 2004/2/19
#1

Tutorial Jquery: Chaining

To show what chaining is I'm going to use some of my own code.
This is a function I use in ajax. When an action is completed and everthing went OK, a message shows up during X time then disappears.
$("#tstme").click(function(){
            
notice('this is ok');
        });
 function 
notice($msg){
        $(
".notice").html($msg);
        $(
".notice").show();
        $(
".notice").delay(3500);
        $(
".notice").slideUp(300);
    }

As you can see, when someone clicks on the link "tstme", function 'notice' is then executed. Here's the logic:
$(".notice").html($msg); set the text inside the div called 'notice'
$(".notice").show(); Show the div since what was initially hidden
$(".notice").delay(3500); Display this message for X amount of time
$(".notice").slideUp(300); Slideup the div

Each time I made a call to $(".notice"), jquery had to process and associate this call to each event. For a small script and few page views you won't notice. But what if your site grows?
This is where chaining comes into play. This same code could be written like this:
$("#tstme").click(function(){
            
notice('this is ok');
        });
function 
notice($msg){
       $(
".notice").html($msg).show().delay(3500).slideUp(300);
    }

Now jquery will associate several event handlers to one event. It obeys the order in which they are placed. This speeds up your code.