Reputation: 49
i tried to do some search but i didn't figured out how to do what do i need.
<ul>
<li class="_0mb"></li>
<li class="_3mb"></li>
<li class="_7mb"></li>
<li class="_14mb"></li>
<li class="_20mb"></li>
<li class="oltre_20mb"></li>
</ul>
what i need to do is to give to the user the ability to switch between different filters clicking on one of those li
tags, this would fire different backgrounds based upon where the user makes the click. Every li
tag has a white background as default and an image when clicked.
I know how to manipulate classes with .addClass
and .removeClass
, but i need to change classes both to the li
the user clicked on and to all of the preceeding li
tags to "activate" the button changing the background image (eg. if the user clicks on _7mb
i need to change the background also to _3mb
and 0_mb
), and i have no idea how to do it.
Similarly i need to change all of the subsequent li
tags "deactivating" them, removing the background image if any, when the user - for example - makes a first click to _20mb
and then a click back to _7mb
.
Upvotes: 0
Views: 527
Reputation: 34168
$('li').click(function () {
$(this).siblings().addBack(this).removeClass('activate notActive clicked');
$(this).addClass('clicked').prevAll().addClass('activate').end().nextAll().addClass('notActive');
});
working example: http://jsfiddle.net/uHmda/
Upvotes: 0
Reputation: 2707
$('li').click(function() {
$(this).addClass('activated');
$(this).prevAll().addClass('activated');
$(this).nextAll().removeClass('activated');
}
Upvotes: 0
Reputation: 755
On the DOM-element you can use .previousSiblings
to get the li elements that come before the li element that the user clicked on.
If you want to use a jQuery object you can call .prev()
on the element that was clicked to get the previous sibling. You will have to call .prev()
again on that sibling and so on in order to get all the previous Siblings. Or you can use the .prevAll()
to get all previous siblings.
your code could look something like this:
$(li).click(function(){
$(this).addClass('clicked');
$(this).siblings().removeClass('clicked');
$(this).prevAll().changeButton();
});
Upvotes: 0
Reputation: 431
Select all previous siblings with jquery and add them css class:
$("li").on('click', function(){
$('li').removeClass('red');
$(this).addClass('red');
$(this).prevAll().addClass('red');
})
Upvotes: 1