AppleBud
AppleBud

Reputation: 1541

How can add class "Active" on click of an li element and remove it from others at the same time?

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

Answers (6)

Wannes
Wannes

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

Jan Drewniak
Jan Drewniak

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

DEMO

Upvotes: 1

Sowmya
Sowmya

Reputation: 26989

Try this

$("#menu li a").click(function() {
  $("#menu li").removeClass('selected');
    $(this).parent().addClass('selected');
});

DEMO

Upvotes: 8

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

You can target the .siblings()

$("#menu li a").click(function() {
    $(this).parent().addClass('selected').siblings().removeClass('selected');
});

Upvotes: 1

codingrose
codingrose

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

Sridhar R
Sridhar R

Reputation: 20418

Try this

$("#menu li a").click(function() {
    $(this).parent().addClass('selected').siblings().removeClass('selected');

    });

DEMO

Upvotes: 21

Related Questions