JQuery: chaining

[Updated: thanks to nyx for detecting that the button ID wasn”t correct]

As I’ve said in the last post, JQuery is all about writing simple and elegant code. One of its most interesting features is chaining. After getting a reference to the custom “JQuery object”, we can invoke several methods exposed by that object. What we didn’t mentioned yet is that many of those objects return a “JQuery object”. In practice, this means that we can invoke another “JQuery method” over the returned instance. Here’s a practical example that hides and shows the button that has been clicked:

<input type="button" value="my button" id="bt" />
<!-- more HTML code--> <
script type="text/javascript"> $( function() { $("#bt").click(function() { $(this).hide(500).show(200); }) }); </script>

As you can see, we’re hiding and then showing the button through the hide and show methods (don’t worry too much about the methods now because we’ll return to them in the future; for now, keep focused on the way you can chain method calls!).

Chaining is a really handy feature , specially if you recall that a JQuery object might wrap several HTML nodes! Suppose that the selector we’ve used ended up wrapping several DOM nodes… If that happened, then you’d end up hiding and then showing all the wrapper DOM nodes. Isn’t that cool? How many lines of  JS code would you need to write if you didn’t had JQuery? Not sure about you, but I don’t even want to think about that scenario…


~ by Luis Abreu on July 13, 2009.

One Response to “JQuery: chaining”

  1. Your example will not work because btn id is “Button1”, but in jQuery function you use “bt” id.

    P.S. I like you blog, there are a lot of intrestiong things.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: