1

I came across this in a jQuery book:

$(elems).mouseenter(function(e) {
           $(this).css("opacity", 0.5);
        }).mouseout(function(e) {
           $(this).css("opacity", 1.0);
        })

I removed much of the code for easier reading and then got this:

$(elems).mouseenter(function(e)).mouseout(function(e))

It seems like in general you can do this?:

$(elems).mouseenter(function(e)).mouseout(function(e)).mouseSOMETHING1(function(e))

Another words using the . to concatenate functions?

Also if I broke this code into say:

$(elems).mouseenter(function(e) {$(this).css("opacity", 0.5);});
$(elems).mouseout(function(e) {$(this).css("opacity", 1.0);});

Is this the same?

Thanks, Jim

1
  • 1
    I did not know I had a vote in the matter in any questions I had asked. I always thought others voted. Thanks for this info will go back to prior questions and look for this fish hook. Commented Aug 29, 2012 at 21:51

4 Answers 4

6

Yes, it is. One of the key features of jQuery is precisely chainability. This is done by returning the jQuery object itself in almost every call, allowing you to pass it along to the next method of the chain.

Sign up to request clarification or add additional context in comments.

Comments

2

It works because all those function returns jQuery object.

   $(elems)  //return jquery object
     .mouseenter(/* ...*/)  //return jquery object
     .mouseout(/* ..*/)     //return jquery object

by this way you can chain as many functions.

$(elems).mouseenter(function(e) {$(this).css("opacity", 0.5);});
$(elems).mouseout(function(e) {$(this).css("opacity", 1.0);});

both methods are functionally same.. except that the 2nd method makes an unnecessary jQuery function call to get $(elems).

1 Comment

My apologies to anyone who took the time to answer any question I have ever asked. It would greatly help for any newbies to Stackoverflow if the checkmark was changed to graphic which read, "Vote this as best answer" or something very similar.
2

What you are talking about is called method chaining and yes, it is well supported in jQuery. Take a look at this quick walkthrough:

Method chaining - The complete jQuery tutorial

Comments

1

Yes $(elems).mouseenter(function(e)).mouseout(function(e)).mouseSOMETHING1(function(e)) is generally acceptable because the jquery functions return the jquery object in question. When you write it out as :

$(elems).mouseenter(function(e) {$(this).css("opacity", 0.5);});
$(elems).mouseout(function(e) {$(this).css("opacity", 1.0);});

It is definitely equivalent to writing it as $(elems).mouseenter().mouseout()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.