views:

1187

answers:

2

All I am trying to accomplish is to be able to have an unordered list of links in which one is clicked, the parent list item is assigned the class "active." Once another link is clicked within that list, it checked to see if "active" is assigned, remove it from that list item, and add it to the most recent clicked links parent list item.

Example:

Step One - User has clicked the link "I am link two"

<ul>
<li><a href="#">I am link one</a></li>
<li class="active"><a href="#">I am link two</a></li>
</ul>

Step Two - User has now clicked the link "I am link one"

<ul>
<li class="active"><a href="#">I am link one</a></li>
<li><a href="#">I am link two</a></li>
</ul>

Pretty simple, but man I beat me up.

+1  A: 

Something like the following ought to do it

$(function() {
    $('li a').click(function(e) {
        e.preventDefault();
        var $this = $(this);
        $this.closest('ul').children('li').removeClass('active');
        $this.parent().addClass('active');
    });
});

Working Demo

Russ Cam
+1 for a more comprehensive solution than the one I've posted.
Lior Cohen
+2  A: 

Assumption: the UL element has the class 'linksList'.

$('.linksList li a').click(function()
{
  $('.linksList li').removeClass('active');
  $(this).parent().addClass('active');
});
Lior Cohen
Thanks a bunch!
Bruno
This will remove the active class from all <li> elementts though, not just those within the respective <ul>. Is that what you want?
Russ Cam
@Russ Cam: if he added an ID/Class to the ul in his example, this could have been easily solved.
Lior Cohen
Modified the answer to match the suggestion in my previous comment.
Lior Cohen
+1 - much better :)
Russ Cam