tags:

views:

28

answers:

1

Say I have an unordered list like so:

<ul>
<li>Some Text</li>
<li>Some Text</li>
<li>Some Text</li>
<li>Some Text</li>
</ul>

I want to use jquery so that when I click a "li", the background changes to blue. So I do this:

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

And the "active" class has as background of blue. However, I can't figure out how to make it so that when I click another "li", the other "li" that has a background of blue stops having a background of blue. I guess what I'm trying to say is how to make only one "li" have a background of blue at a time--using jquery.

+3  A: 

You can do this:

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

This approach selects the current .active and removes the class from it before applying it to the one you just clicked.

Nick Craver
Yes that does it but it also removes the active class from the one you click on. I need the last one that was clicked to have the blue background.
codedude
oh nevermind...I messed something up in my code. Now it works. Thanks a lot!
codedude