Reputation: 69
For example, if i have a drop down navigation, i would like the active link to have a different color than the rest of the navigation link.Something similar to: http://www.emerson.edu/.
Here is my jquery code:
if ($(".testHeader a#" + thisID).hasClass("active")) {
$(".testHeader a").removeClass("active");
} else {
$(".testHeader a").removeClass("active");
$(".testHeader a#" + thisID).addClass("active");
}
Where my active
class is a css style that changes the link color.
The problem that i am having is that each link is staying active if i click more than 1 link. I actually want only want one link to be active when being clicked. What is wrong my jquery? Thanks!
Upvotes: 0
Views: 373
Reputation: 5399
Use this
. First remove all the active classes when the event is triggered and then add the class on to the currently selected object, this
.
$('a').click(function(){
$('a').removeClass('active');
$(this).addClass('active');
});
EDIT: To close it by clicking again, do this.
$('a').click(function(){
if($(this).hasClass('active')){
$(this).removeClass('active');
}else{
$('a').removeClass('active');
$(this).addClass('active');
}
});
Upvotes: 0
Reputation: 22570
It would help to know what "event" this takes place on.
If it is a hover
event. Then you could do something like:
$('.testHeader a').hover(function(e) { $(this).toggleClass('active'); });
// However, if any of your links are dynamic or a half dozen other issues, this could misfire
// Thus I would really suggest the long form as:
$(document).on('mouseenter', '.testHeader a', function(e) {
$(this).addClass('active');
})
.on('mouseleave', '.testHeader a', function(e) {
$(this).removeClass('active');
})
If on click
event then you could do:
$(document).on('click', '.testHeader a', function(e) {
$('.testHeader .active').removeClass('active');
$(this).addClass('active');
})
Upvotes: 0
Reputation: 12305
You can just say
$(".testHeader a#"+thisID).toggleClass("active");
Upvotes: 1