Andy Dwyer
Andy Dwyer

Reputation: 716

Don't remove class on click

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

Answers (5)

Jai
Jai

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

algorhythm
algorhythm

Reputation: 8728

$(function(){
    $(".uibutton").click(function(e){
        e.preventDefault();
        if ($(this).hasClass('active')) {
            $(this).removeClass("active");
        } else {
            $(this).addClass('active');
        }
    });
});​

Upvotes: 0

Siva Charan
Siva Charan

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

Alexandros B
Alexandros B

Reputation: 1891

You can modify your code like so

$(function(){
  $(".uibutton").click(function(e){
    e.preventDefault();
    var button = $(this);

    button.toggleClass("active");
  });
});

Upvotes: 1

Horen
Horen

Reputation: 11382

You can use the toggleClass function together with removing removeClass("active"):

Demo

Side note: If you are using jQuery UI you could also consider the checkbox buttons

Upvotes: 2

Related Questions