0

Since I learned jQuery I've always wondering how does jQuery execute a function after another just by adding dots . (dont know it real name, sorry for that);

$("#somediv").fadeIn("fast").css("background","blue");

When fade effect finished then the CSS function execute. Its like if you can execute whatever function you want one after another.

How can I do that?

Note: If I named something wrong, please correct me, I just want to learn.

Sparky
  • 98,165
  • 25
  • 199
  • 285
Misters
  • 1,337
  • 2
  • 16
  • 29

3 Answers3

5

It returns the same type of object, here's a really trivial example that demonstrates the technique:

var Counter = function(){
    this.val = 0;    
};

Counter.prototype.increment = function(){
    ++this.val;
    return this;
};

Counter.prototype.decrement = function(){
    --this.val;
    return this;
};

Counter.prototype.log = function(){
    console.log(this.val);
    return this;
};

var o = new Counter();
o.increment().increment().decrement().log().increment().log();
Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
3

It is called method chaining, where a method returns the object which it called it.

You can also refer the following post on the subject
How can jQuery do method chaining
how does jquery chaining work?

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

The short answer is quite straightforward. Each method returns the collection of elements that match the selector passed to it, allowing for that same collection to be passed into the next chained method.

look in source for return this

charlietfl
  • 170,828
  • 13
  • 121
  • 150