Reputation: 716
I have the following jQuery code which supplements a CSS-created navigation bar. Currently, the code removes the active
class when a separate navigation button is pressed.
I'd like for the code to not remove the active
class and allow more than one button to be active at a time. How can this be accomplished?
$(function(){
$(".uibutton").click(function(e){
e.preventDefault();
$(".uibutton").addClass("active").not(this).removeClass("active");
});
});
Full code on jsFiddle: http://jsfiddle.net/KhyK7/
Upvotes: 1
Views: 464
Reputation: 74738
You can target the clicked event item and just add the class, easy...
$(function(){
$(".uibutton").click(function(e){
e.preventDefault();
$(e.target).addClass("active");
});
});
Upvotes: 1
Reputation: 8728
$(function(){
$(".uibutton").click(function(e){
e.preventDefault();
if ($(this).hasClass('active')) {
$(this).removeClass("active");
} else {
$(this).addClass('active');
}
});
});
Upvotes: 0
Reputation: 18064
Just do this way:-
$(function(){
$(".uibutton").click(function(e){
$(this).addClass("active");
});
});
As per UI, what you want is wrong.
Refer LIVE DEMO
Upvotes: 1
Reputation: 1891
You can modify your code like so
$(function(){
$(".uibutton").click(function(e){
e.preventDefault();
var button = $(this);
button.toggleClass("active");
});
});
Upvotes: 1
Reputation: 11382
You can use the toggleClass
function together with removing removeClass("active")
:
Side note: If you are using jQuery UI you could also consider the checkbox buttons
Upvotes: 2