Search code examples
javascriptjquerygreasemonkey

Button toggle-class remains active upon pressing another button


I'm writing a Greasemonkey script and having a problem setting the active states for two buttons I'm adding, each for toggling.

I've added code to assign class. The problem occurs when switching buttons.

For instance, when I press Button A, it becomes active. But then, if I press Button B, Button A remains active. Thereby leaving me with two buttons in an active state.

I know I can remove the active class by pressing my active button again prior going to another button. However I would like to achieve a function whereby, if Button A is active, and I press Button B, then Button A loses its active class, and vice versa.

Here is the code I'm using that's assigning class to my buttons:

$('#ButtonA').toggle(function () { 
    $("#ButtonA").addClass("active"); }, function () {
    $("#ButtonA").removeClass("active");
});

$('#ButtonB').toggle(function () {
    $("#ButtonB").addClass("active"); }, function () {
    $("#ButtonB").removeClass("active"); 
});

Solution

  • You simply add one line in your first callback for each button to remove active class from any active button.

    $('#ButtonA').toggle(function() {
        $('button.active').click(); // Remove active class from any active button.
        // you may adapt 'button.active' to select the proper buttons
        $('#ButtonA').addClass("active");
    }, function() {
        $('#ButtonA').removeClass("active");
    });​
    


    But, use only one block of code for all the buttons, like this;

    $('#ButtonA, #ButtonB, #ButtonC').toggle(function() { // this refer to the just clicked button.
        $('button.active').click(); // Remove active class from all other buttons.
        $(this).addClass("active");
    }, function() {
        $(this).removeClass("active");
    });
    

    instead of copying and pasting.

    See http://jsfiddle.net/fNtPP/1/ for a clean refactored code showing an example with 3 buttons.