I have an ul-list that contains li-elements. When the user clicks on one of these li elements a class should be added to that element.
This is easy to setup, however, when the other li-element is clicked I want the "active"-class to be removed from the non-active li.
I have made a jsfiddle of the problem: http://jsfiddle.net/tGW3D/
There should be one li-element that is red at any one time. If you click the second and then the first, only the first should be red.
This will remove the active class from each li that have active and than will add to the Element which was clicked.
$('body').on('click', 'li', function() {
$('li.active').removeClass('active');
$(this).addClass('active');
});
You can use siblings
and removeClass
methods.
$('li').click(function() {
$(this).addClass('active').siblings().removeClass('active');
});
http://jsfiddle.net/Lb65e/
Just remove all instances of .active
first, and then add it:
$('ul li').on('click', function() {
$('ul li.active').removeClass('active');
$(this).addClass('active');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With