JQuery "active" class assignment

All I'm trying to do is have an unordered list of links that you click on, the parent class is set to the class "active". After another link was clicked on this list, she checked if "active" was assigned, remove it from this list item and add it to the list of the last items in the list of favorite links.

Example:

Step One - The user clicked the link "I will contact 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 - The user clicked the link "I connect 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.

+6
jquery state sticky
source share
3 answers

Assumption: The UL element has a class of 'linksList'.

 $('.linksList li a').click(function() { $('.linksList li').removeClass('active'); $(this).parent().addClass('active'); }); 
+10
source share

Something like the following should 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

+7
source share

This question is a bit outdated, but I think there is still room for improvement.

"Traditional" binding of local events:

 $("ul a").click(function(){ $(this).parent("li").addClass("active") .siblings().removeClass("active"); # return false to cancel the default action (eg follow the link): return false; }); 

Now the same thing, using delegation delegation through delegate () (jQuery +1.4.2). Allows you to dynamically add additional> li> a without having to replay the event:

 $("ul").delegate("a", "click", function(){ $(this).parent("li").addClass("active") .siblings().removeClass("active"); # return false to cancel the default action # and prevent it from bubbling (further) up: return false; }); 

Change "ul" to everything that matches exclusively the list (s), for example. ".linksList", "#nav", etc.

+1
source share

All Articles