CaseyHunt
CaseyHunt

Reputation: 535

Add active class without removing when clicked twice

Fiddle: http://jsfiddle.net/vuKqw/60/

What would allow the 'active' class to remain attached to an item when it is clicked twice? The intended behavior is that only whe a NEW tab is clicked does it change classes. Otherwise, if the same tab is clicked twice for example, it should remain 'active' not toggle between active and inactive.

$('nav li a').click(function() {
    $(this).parent().toggleClass('active').siblings().removeClass('active');
});

Reference: Jquery change class on click menu


I ended up breaking it out into a function: http://jsfiddle.net/vuKqw/72/

function tabchange() { 
 var parent = $(this).parent();
    if(!parent.hasClass('active')) {
        parent.addClass('active').siblings().removeClass('active');
}
};

$('nav li a').click(tabchange)​

Thank you @Madbreaks for the answer- that pointed me in the right direction.

Upvotes: 1

Views: 599

Answers (1)

Madbreaks
Madbreaks

Reputation: 19549

Check first to see if the parent is active:

$('nav li a').click(function() {
    var parent = $(this).parent();
    if(!parent.hasClass('active')){
        parent.addClass('active').siblings().removeClass('active');
    }
});

Note the use of 'addClass' instead of 'toggleClass' - better to be more specific in situations where you know exactly what you're doing (the intent there is only ever to add the class).

Cheers

Upvotes: 2

Related Questions