Link 1

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!

+4
source share
3 answers
 $("a").click(function(){ $("a.active").removeClass("active"); $(this).addClass("active"); }); 

Edit: added jsfiddle

http://jsfiddle.net/LJ6L5/

+12
source

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> 
+2
source

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); }); 
0
source

Source: https://habr.com/ru/post/1334921/


All Articles