Change class to tag

I would like to change the tag class on click.

jsFiddle here: http://jsfiddle.net/9u8Nc/

Got this HTML code:

<ul class="tags"> <li> <a href="javascript:void(0)" class="tag">Aventure</a> <div class="user-info"> <p><b>Aventure</b> <br> + 2.300 activités</p> </div> </li> <li> <a href="javascript:void(0)" class="tag">Famille</a> <div class="user-info"> <p><b>Famille</b> <br> + 1.500 activités</p> </div> </li> <li> <a href="javascript:void(0)" class="tag">Gourmet</a> <div class="user-info"> <p><b>Gourmet</b> <br> + 500 activités</p> </div> </li> </ul> 

When I click the "I want to change the style" button.

When I click on it again, I need a style back.

Try it, but it won’t work.

 $('.tag').click(function() { $(this).addClass('active'); }); 
+4
source share
2 answers

You can use the toggleClass function:

 $('.tag').click(function() { $(this).toggleClass('active'); }); 

When you click, it sets the class if it is not installed, or removes it if it is installed.

In your css replace

 .tag .active 

with

 .tag.active 

like .tag .active does not correspond to an element with both classes, but to an element with class active in another element of the tag class.

Demonstration

+4
source

You can use toggleClass

Live demo

 $('.tag').click(function() { $(this).toggleClass('active'); }); 
+2
source

All Articles