X

LATEST #JQUERY NEWS

Using Method Chaining in jQuery


Using method chaining in jQuery helps to ensure that your code stays as lightweight as possible. Method chaining allows you to apply many methods to one single selector, thus limiting the amount of times you have to re-write the same selector over and over again. To see how it works, here’s some jQuery code that doesn’t use method chaining:

$(“.main”).css(“color”, “red”);
$(“.main”).addClass(“selected”);
$(“.main”).slideDown();

The example above uses three different $(“.main”) selectors, one for each method. Not only is this annoying and time consuming to write, but using the same selector over and over again can slow down your code. This is where method chaining comes in. The same example above using a method chaining technique would look like this:

$(“.main”).css(“color”, “red”).addClass(“selected”).slideDown();

As you can see from the example above, method chaining will make your code look cleaner and more concise. It’s a technique you should definitely employ if you’re applying more than one method to a single selector.

Recently Published

Screen Shot 2017-04-23 at 10.15.41 AM
»

How to Use jQuery to Create a Sticky Navigation on Scroll

Creating “sticky” elements is something that can often be ...

article image
»

How to Use jQuery’s Keystroke Methods

jQuery has a few built-in keystroke methods that are all triggered by ...

article image
»

How to Change iFrame Styling Using jQuery

If you’ve ever had the displeasure of working with iFrames, ...

article image
»

How to Use jQuery to Create Blinking Text

Blinking text is one of those cool features that you never actively ...

article image
»

Convert Images to Black and White using jQuery

Converting an image to black and white is no longer a manual event. ...

article image
»

How to Disable Right-Click Menu Using jQuery

There can be dozens of reasons why you may want to disable right ...

article image
»

How to Optimize jQuery Code for Better Performance

jQuery is the most popular client side library, in fact almost every ...

article image
»

Using Head.js to Load All Your JavaScript

In the past few years, client side frameworks/libraries have become ...

article image
»

How to Detect Browser Using jQuery

One of the more frustrating parts of creating a new web project is ...