Reputation: 15303
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
Upvotes: 1
Views: 258
Reputation: 75327
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.
Upvotes: 4
Reputation: 888293
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()
Upvotes: 3