1

i wrote this function to toggle a class name, of next div using jquery chaining function, but it doen't work...

  $('a.back-btn,a.front-btn').click(function(e){
        e.preventDefault();
        $(this).toggleClass('back-btn front-btn').end()
        .next().find('.models').toggleClass('rotated');
})

in case if i write separate line, then it works fine :

$('a.back-btn,a.front-btn').click(function(e){
            e.preventDefault();
            $(this).toggleClass('back-btn front-btn');
            $(this).next('.models').toggleClass('rotated'); // separate line
        })

what is the issue with my chaining function, how it need to end a process in case if i use the chaining. i used end(), is it wrong? any best clarification to use end()?

thanks in advance

2
  • Your two pieces of code aren't equivalent. $(this).next('.models') returns the element after this if it has the class models. $(this).next().find('.models') returns all elements that have the class models and are descendents of the element after this. Honestly, I'm not entirely convinced that the .end() was the only issue, and rather you were writing code that wasn't what you actually meant or wanted. Commented Feb 20, 2012 at 15:27
  • Reading the jQuery doc for .end() should clear things up. The .end() is not needed and is messing things up. Commented Feb 20, 2012 at 15:56

2 Answers 2

4

If you remove end(), it'll work. Using end() only applies when you have ran a function in the current jQuery chain which altered the set you were working on.

$('a.back-btn,a.front-btn').click(function(e){
    e.preventDefault();
    $(this).toggleClass('back-btn front-btn').next('.models').toggleClass('rotated');
});

Here's a valid (but completely pointless) use of end():

$(this).next('.models').toggleClass('rotated').end().toggleClass('back-btn front-btn');

The next() method alters the current set of jQuery elements we're working on, so the toggleClass method works on the next .models element. We then end() to return to $(this), on which we toggle the rotated class.

See the end() documentation for another explanation/ example.

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

Comments

3

The end() function ends a child selection.
You shouldn't use it here.

end() would be used like this:

$(something)
    .children()
        .hide()
    .end()    //Go back to the original something
    .animate()

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.