i know this is incredibly easy but I have been writing and rewriting this function for an hour with no success:
On click I want to add "active" to the <li>
of the clicked link and remove "active" from all the other <li>
's in the navbar.
HTML:
<nav>
<ul>
<li><a href="http://0327ea8.netsolhost.com/#home" class="home">Home</a></li>
<li><a href="http://0327ea8.netsolhost.com/blog/" class="blog">Blog</a></li>
<li><a href="http://0327ea8.netsolhost.com/#catalog" class="catalog">Catalog</a></li>
<li><a href="http://0327ea8.netsolhost.com/#authors" class="authors">Authors</a></li>
<li><a href="http://0327ea8.netsolhost.com/#store" class="store">Store</a></li>
</ul>
</nav>
jQuery:
// NAVBAR ADD ACTIVE
$("nav ul li a").click(function(){
$("nav ul li").removeClass('active');
$(this).stop().animate();
$(this).parent().addClass('active');
});
This is adding the classes just fine but I can't get it to remove.
I've also tried separating it into to separate functions with no luck.
I have the .stop().animate() in there because I have a .animate() on the hover state of the links.
thanks!
edit:
this is the jQuery for the hover and the reason I have .stop().animate()
$("nav ul li a, aside ul li.categories a, div.posts div.foot a").hover(function(){
$(this).animate({'backgroundColor' : '#edf5e9'}, 200);
},function() {
$(this).animate({'backgroundColor' : '#ccd4c8'}, 600);
});
I'm not sure why the .stop().animate() is wrong. If I don't have .animate() the active class won't stick, if I do, the active class does.
I still can't get the class to remove though :-/
Try this:
$(this).parent().siblings().removeClass('active');
Try something even simpler:
$('li.active').removeClass('active');
来源:https://stackoverflow.com/questions/4718877/jquery-add-remove-class-from-parent