user3400080
user3400080

Reputation: 211

jquery click add and remove class

I have a list items and when I click Li element, add class "active", and others remove class

Here is Fiddle [http://fiddle.jshell.net/9yNtq/] And codes

<div class="boxList">
                <table>
                <tr>
                    <td>
                        <a href="#" data-ajax="false"><span>list1</span></a>
                    </td>
                    <td>
                        <a href="#" data-ajax="false"><span>list2</span></a>
                    </td>
                    <td>
                        <a href="#" data-ajax="false"><span>list3</span></a>
                    </td> 
                </tr>  
                </table>
            </div>


.boxList { margin:5px 0 0 0;   }
.boxList table { table-layout:fixed; width:100%;   }
.boxList td { width:33.3%; padding:0; margin:0; text-align:center;  }

.boxList a {   width:100%; font-size:1.07em; font-weight:bold;  height:62px; color:#000; line-height:1.3;  }
.boxList a span {   padding:0; margin:0;  width:100%; height:62px;  }
.boxList a.active { background:blue }


$('.boxList a').click(function(){ 
                $('.boxList a').removeClass("active"); 
                $(this).addClass("active"); 
            });

My question is... How to remove "active" class when click same element again ?

Upvotes: 1

Views: 1792

Answers (2)

Savata Khamkar
Savata Khamkar

Reputation: 58

You might be looking for this...

$('.boxList a').click(function(){ 

 if($(this).hasClass('active')){       
    $('.boxList a').removeClass("active"); 
 }
 else{

    $('.boxList a').removeClass("active");         
    $(this).addClass("active"); 
 }
});

Here is Example

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82231

You can use toggleClass('classname') for that. also you need to remove currently clicked element from selector using .not():

 $(this).toggleClass("active"); 

Full Code:

$('.boxList a').click(function(){ 
            $('.boxList a').not(this).removeClass("active"); 
            $(this).toggleClass("active"); 
});

Working Demo

Upvotes: 4

Related Questions