Chaining in jQuery
Chaining in jQuery let’s you write code that is faster to execute, easier to read, and easier to maintain. Even if you haven’t heard of chaining, if you’ve worked with jQuery it’s likely that you’ve already seen jQuery code utilizing chaining.
So what does it look like? Let’s compare two snippets of code—they accomplish the exact same thing, but one uses chaining, and the other one doesn’t:
Yup, it’s shorter—but what’s so great about this? And why does that even work?
How it Works
Almost all jQuery methods return a jQuery object. I.e., after you’ve run a method on your selection, you can continue running more methods. You can even change your selection (in this case with
find()), and continue to run methods on your new selection.
The obvious benefit is you write less code. It’s easier and faster to write—and to manage. But your code also runs faster. Look at the first snippet without chaining. Every single row tells jQuery to first search the entire DOM for an object, and then run a method on that object. When we use chaining, jQuery only has to search for the object one single time. And when we use
find() to change the selection, we use the already selected object as a starting point—in this case
Putting it to Use
Chaining even works with events, and there’s a whole arsenal of methods simply to change your selection—a task called traversing. Here’s a simple chaining of events; we add a click event and a mouseleave event to
Easy, right? Here’s a snippet from this very blog you’re reading:
This snippet creates the effect when you hover an entry on the startpage (notice that I use
mouseenter() and not
mouseover()—there’s a big difference). It uses traversing to find the thumbnail—fades the thumbnail to 80% during 0.3 seconds—then uses traversing to target the View Case Study button, which fades in.
This was a crash course in chaining in jQuery, and I promise we’ll dig in further later on. If you can’t wait to learn more, here’s some further reading: