Reputation: 1541
I am trying to create a menu in which I want to change the CSS of an li element on click while at the same time, CSS of other li's should remain the same.
My menu is:
<ul id="menu">
<li><a href="#">Parent 1</a> </li>
<li><a href="#">item 1</a></li>
<li><a href="#">non-link item</a></li>
<li><a href="#">Parent 2</a> </li>
</ul>
and my jquery to add CSS to the selected element is:
$("#menu li a").click(function() {
$(this).parent().addClass('selected');
});
However, right now, I am unable to remove the added CSS from a non-selected element. Is there anyway I can implement this?
Upvotes: 6
Views: 71742
Reputation: 359
Try this, this will always work
$("#menu li a").on('click', function(e){
$("#menu .active").removeClass('active');
$(this).parent().addClass('active');
e.preventDefault();
});
Upvotes: 5
Reputation: 1394
Or for the javascript-free approach, you can use radio buttons:
http://www.onextrapixel.com/2013/07/31/creating-content-tabs-with-pure-css/
and use the sibling selector to style them
input[type='radio']:checked + label
Upvotes: 1
Reputation: 26989
Try this
$("#menu li a").click(function() {
$("#menu li").removeClass('selected');
$(this).parent().addClass('selected');
});
Upvotes: 8
Reputation: 17366
You can target the .siblings()
$("#menu li a").click(function() {
$(this).parent().addClass('selected').siblings().removeClass('selected');
});
Upvotes: 1
Reputation: 15709
$("#menu li a").click(function(){
// Remove active if this does not have active class
if(!($(this).closest("li").hasClass("active"))){
$(this).closest("#menu").find("li.active").removeClass('selected');
}
$(this).closest("li").addClass('selected');
});
Upvotes: 0