Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

E.g.: $(".element").fadeOut().delay(500).fadeIn();

Why can I run multiple functions on a single jQuery object and when can I use this feature? Is there any tutorial/documentation on this?

share|improve this question
add comment

4 Answers 4

up vote 19 down vote accepted

This is known as chaining and helps you create a fluent interface. Each function returns a reference to the current jQuery instance, which is why you can chain the calls together.

You first create a jQuery instance using $('.element'), which returns an insance of the jQuery object; it's essentially like a constructor. Then each member function of the jQuery object, returns a reference to this, which is basically the owning instance of that function. So instead of doing this:

var jQueryObj = $(".element");
jQueryObj.fadeOut();
jQueryObj.delay(500);
jQueryObj.fadeIn();

You can do it all in one line, because each function more-or-less kind of looks like this (this is a very simple example):

function fadeOut() {
   //jQuery code
   //...

   return this;
}

It is important to note that not all jQuery functions are not chainable; some do not return a reference to the jQuery instance and so you cannot chain them. Examples include .html(), .text(), and .val(). These return the actual content that you want (HTML, text, or value of an input element for example). It wouldn't make sense to chain in these cases.

Here's a very simple example that shows you how chaining works:

var Starship = function() {
    this.name = "USS Enterprise";
    this.registry = "NCC-1701";
    this.shipClass = "Constitution";
};

Starship.prototype.name = function(name) {
    this.name = name;
    return this;
};

Starship.prototype.registry = function(registry) {
    this.registry = registry;
    return this;
}

Starship.prototype.shipClass = function(shipClass) {
    this.shipClass = shipClass;
    return this;
}

Starship.prototype.print = function() {
    console.log(this.name + " " + this. registry + " " + this.shipClass);
}

Now you can create an instance like so:

var starship = new Starship()
    .name("USS Enterprise")
    .registry("NCC-1701-E")
    .shipClass("Sovereign");

You can then also call starship.print(), but notice that it does not return this, which means you cannot chain anything after that.

jQuery's documentation will go over which methods are chainable and which are not. If the documentation says that the function returns jQuery, then it is chainable; otherwise it is not. Also take note that certain methods are chainable depending on what parameters are passed. For example, the .attr function, which lets you set an attribute, is chainable only when setting an attribute via .attr(attrName, attrValue). When only supplying one argument (.attr(attrName)), it returns the value of the attribute and hence is not chainable.

share|improve this answer
5  
Maybe add that some do not, like .html(), .text(), parent, next, prev, exit ... –  PitaJ yesterday
    
@PitaJ Will do so. –  Vivin Paliath yesterday
1  
"It is important to note that all jQuery functions are not chainable" should probably be "It is important to note that not all jQuery functions are chainable"... "all x are not y" implies that "none x are y", while I'm pretty sure you mean "not all x are y", which implies "some x are not y" –  Bob 22 hours ago
    
@Bob you are absolutely right; I forgot the "not"! –  Vivin Paliath 15 hours ago
add comment

Load the jQuery site in your browser and click on API Documentation. Each function has a table that includes a returns statement. If it says this:

Returns jQuery

... you can use chaining.

Otherwise, you cannot, e.g.:

Returns String

In some methods, the return type depends on parameters passed:

attr - Returns jQuery

attr - Returns String

share|improve this answer
1  
+1 for noting that parameters passed can effect the return type –  Brett Weber yesterday
add comment

This is accomplished using design-pattern known as a "Fluent Interface". It is also known as 'chaining'.

FOR EXAMPLE:

var Car = function() {

        var speed, color, doors;

        this.setSpeed = function(speed) {
                this.speed = speed;
                **//Returns the reference to the calling `car` object** 
                return this; 
        };

        this.setColor = function(color) {
                this.color = color;
                **//Returns the reference to the calling `car` object** 
                return this; 
        };

        this.setDoors = function(doors) {
                this.doors = doors;
                **//Returns the reference to the calling `car` object** 
                return this; 
        };

};

// Fluent interface
**//Each method returns a reference to the object itself**
**//so the next method chain is refering back to the previous returned value**
**//ie - itself, the orginal object that started the call chain**
myCar = new Car();
myCar.setSpeed(100).setColor('blue').setDoors(5);

// Example without fluent interface
**// normal, non fluent style, where each method returns Void**
**// so you need to start with the object reference yourself each time**
myCar2 = new Car();
myCar2.setSpeed(100);
myCar2.setColor('blue');
myCar2.setDoors(5);
share|improve this answer
    
Fantastic answer! –  Brett Weber yesterday
add comment

As @vivinpaliath stated, this is something called chaining.

It works because almost every method in jQuery returns a reference to the original object (or in a few cases, the edited object).

You can chain any built in methods with exception of methods that return specific values.

Examples of such are css("cssProperty"), attr("attribute"), prop("property"), html(), text(), and val()

Here's a good article on jQuery chaining

share|improve this answer
    
"on pretty much any built in methods with a few exceptions" ... Any way yould list these out? otherwise this answer is adding no value that isn't already stated by the popular answer –  Brett Weber yesterday
    
@BrettWeber Vivin Paliath has already beaten me to it –  dartanian300 yesterday
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.