Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Remove class if other element is clicked

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.

like image 214
Albin N Avatar asked Oct 02 '12 08:10

Albin N


3 Answers

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');
});
like image 72
Rosmarine Popcorn Avatar answered Nov 17 '22 03:11

Rosmarine Popcorn


You can use siblings and removeClass methods.

$('li').click(function() {
    $(this).addClass('active').siblings().removeClass('active');
});

http://jsfiddle.net/Lb65e/

like image 25
undefined Avatar answered Nov 17 '22 01:11

undefined


Just remove all instances of .active first, and then add it:

$('ul li').on('click', function() {  
    $('ul li.active').removeClass('active');
    $(this).addClass('active');    
});
like image 5
BenM Avatar answered Nov 17 '22 02:11

BenM