One of the best thing about jQuery is it’s chain ability for almost all it’s methods. If “chain ability” sounds hebrew, here’s a little explanation what it is.
Let’s say you have a <div id=”myDiv”>Lorem Ipsum </div>
And you need to do the following
- Change the height to 150px
- Change the opacity to 0.8
- Add a class called “pClass”
- And set the text inside the div like “We are the world”
So, what would you do in normal circumstances? You write four lines of code. Like if you use jQuery in conventional way you’d probably write
1 2 3 4 | $("#myDiv").css("height","150px"); $("#myDiv").fadeTo(500,0.8); $("#myDiv").addClass("pClass"); $("#myDiv").text("We are the world"); |
But if we use method chaininig we’d simply write
$("#myDiv").css("height","150px").fadeTo(500,0.8).addClass("pClass").text("We are the world");
Looks messy ? I don’t think so. It’s readable unless you put quite a lot of methods to an object which is very unlikely. So that is chaining.
Behind the screens , chaining is simply done by returning the object itselft after applying the method. It’s quite like how we use methods in Javascript Object like
var myString="Lorem Ipsum Dolor";
pString= myString.toLowerCase().substring(0,5);
And this is a gift when we have options to do things like that. Who wants to write more code when there’re ways to make it short ? At least I don’t. So almost all of the methods
in jQuery has this chainability. All the methods that chain, returns the whole jQuery object itself so that more methods can be applied to it.
You can see the above code running here.











































Recent Comments