Adding a class when you click an anchor label
Let's say I have the following HTML ...
<a class="active" href="#section1">Link 1</a> <a href="#section2">Link 2</a> When I click on link 2, I would like it to get the active class and remove the class from link 1 itself, so that it really becomes:
<a href="#section1">Link 1</a> <a class="active" href="#section2">Link 2</a> This should work both ways. I.e. any click on the link gets the class and removes it from another.
How can this be done using jQuery? Thanks in advance!
Just use: addClass and removeClass
But first, limit your activated links to a second class ("activated") so as not to affect other links on the 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> HTML:
<a class="myrefclass" href="#section1">Link 1</a> <a class="myrefclass active" href="#section2">Link 2</a> JS:
var ref = $("a.myrefclass"); $(ref).bind('click', function() { if (!$(this).hasClass("active")) { $(ref).removeClass("active"); $(this).addClass("active); } }); JS II (for comments):
var ref = $("a.myrefclass"); $(ref).bind('click', function(ev) { if (!$(this).hasClass("active")) { ev.stopPropagation(); return false; } $(ref).removeClass("active"); $(this).addClass("active); });