JQuery: chaining

Published Mon, Jul 13 2009 22:27

[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…

Filed under:

Comments

# nyx said on Tuesday, July 14, 2009 1:41 AM

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.

# LA.NET [EN] said on Sunday, July 19, 2009 4:19 PM

Even though I’ve said that you could use the jQuery method for creating new HTML elements from strings

# ASPInsiders said on Sunday, July 19, 2009 5:15 PM

Even though I’ve said that you could use the jQuery method for creating new HTML elements from strings,

# LA.NET [EN] said on Monday, July 20, 2009 6:52 AM

Now that we now how to create new HTML elements, it’s time to go on and see how we can interact with

# ASPInsiders said on Monday, July 20, 2009 7:38 AM

Now that we now how to create new HTML elements, it’s time to go on and see how we can interact with

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover