views:

42

answers:

1

I have a few lists, and when a user clicks on an item I would like it to change the class to current, but if a users then clicks on another item in the same list to switch that to current and remove the current from the previous item selected.

any quick examples, i know this is probably out there already but couldn't find a good example.

<ul id="list">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
</ul>

So if you click on item 1 it will be class current, but switch off if you click on item 2.

+5  A: 
$('ul#list li').click(function(){
   $(this).addClass('current').siblings().removeClass('current');
});

references

simple demo


It would be easy if you use the li in adding/removing current because of the siblings. But if you wan't to use the anchors, do it this way,

$('ul#list li a').click(function(){
   var li = $(this).parent();
   li.find('a').addClass('current');
   li.siblings().find('a').removeClass('current');
   return false;
});

or if you just want to use anchors just for the click event and still add/remove current on li, do this,

$('ul#list li a').click(function(){
   var li = $(this).parent();
   li.addClass('current').siblings().removeClass('current');
   return false;
});
Reigel
Is there a reason why it would not remove the class="current" from an anchor in the list. I had to change it to:$('ul#list li a').click(function(){and it is adding the class but not removing it??
Xtian
please see edits
Reigel
This worked very well. My question is, applying that function to multiple <ul> on the same page doesn't work, but I feel as though it should since:var li = $(this).parent();should target the just the anchors in ul#list li and not ul#list2 lior am I totally wrong in assuming that?
Xtian
`var li = $(this).parent(); should target the just the anchors in ul#list li and not ul#list2 li` - you're correct.
Reigel