Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a class on click of Anchor tag

Tags:

html

jquery

css

Lets say I have the following HTML...

<a class="active" href="#section1">Link 1</a>  
<a href="#section2">Link 2</a>  

When a link 2 is clicked I would like it to receive the active class and remove the class from link 1 itself so it would effectively become:

<a href="#section1">Link 1</a>  
<a class="active" href="#section2">Link 2</a>

This should work both ways. Ie. whatever link is clicked gets the class and removes it from the other.

How can this be done with jQuery? Thanks in advance!

like image 331
Vivek Avatar asked Jan 10 '11 13:01

Vivek


2 Answers

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

Edit: added jsfiddle

http://jsfiddle.net/LJ6L5/

like image 188
switz Avatar answered Sep 28 '22 07:09

switz


Just use: addClass and removeClass

But first limit your activable links with second class ('activable') to not affect other links on page:

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

With HTML:

<a class="activable active" href="#section1">Link 1</a>  
<a class="activable" href="#section2">Link 2</a>  
like image 45
gertas Avatar answered Sep 28 '22 07:09

gertas