A Quick Guide

Chaining in jQuery

Chaining in jQuery let's you write code that is both faster to execute, and easier to maintain. Let's compare two snippets of code—they accomplish the exact same thing, but one uses chaining, and the other one doesn't.

// No chaining
$("#menu").fadeIn("fast");
$("#menu").addClass("active");
$("#menu").css("marginRight", "10px");
    
// vs. with chaining
$("#menu").fadeIn("fast")
  .addClass("active")
  .css("marginRight", "10px");

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 #menu.

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 #button.

// Chaining of events
$("#button").click(function(e){
  alert("You clicked me!");
}).mouseleave(function(e){
  alert("You left me!");
});

Easy, right? Here's a snippet from this very blog you're reading:

$("#thumbnails li").mouseenter(function(e){
  $(this)
      .find("img")
        .stop()
        .animate({opacity: 0.8}, 300)
      .end()
      .find(".viewcasestudy")
        .fadeIn("fast");
});

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.

Learn More

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:

Published on 24 Apr 2010