1

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 ?

0

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.