Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  147] [ 1]  / answers: 1 / hits: 20363  / 11 Years ago, tue, march 26, 2013, 12:00:00

I have a navigation that shows an active state using class=active. When a link is clicked, I need to add the active class to to the clicked link, and remove the active class from all other links.



Here's my code:



<div id=referNav>
<div id=referLink1><a href=javascript:; onClick=changeClass(); class=active></a></div>
<div id=referLink2><a href=javascript:; onClick=changeClass(); class=></a></div>
<div id=referLink3><a href=javascript:; onClick=changeClass(); class=></a></div>
</div>


Any help would be greatly appreciated!


More From » jquery

 Answers
9

Try this:



function changeClass() {
$('#referNav a').removeClass('active');
$(this).addClass('active');
}


And you should also bind the function in javacript like so:



$('#referNav a').on('click', changeClass);


That way, as Travis J points out in the comments, $(this) will reference the correct object.



jsFiddle


[#79337] Tuesday, March 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dylondaytond

Total Points: 92
Total Questions: 88
Total Answers: 96

Location: China
Member since Fri, Jan 15, 2021
3 Years ago
dylondaytond questions
Tue, Jun 22, 21, 00:00, 3 Years ago
Thu, May 7, 20, 00:00, 4 Years ago
;