Search code examples
jqueryhyperlinkclickremoveclasstoggleclass

Jquery - Toggle class on click of button / Remove class on click of body and other buttons with same class


I have different buttons with the same class. Each button have a "+" with :after. I want to show a "-" if a button is clicked and remove the "-" when one of the other button is clicked, the rest of the window is clicked or the same button is clicked again.

This is what I have so far:

var removeClass = true; 
$(".button").click(function () {
    /* $(".button").removeClass('bclose'); */
    $(this).toggleClass('bclose');
    removeClass = false;
});

$(".button").click(function() {
    removeClass = false;
});

$("html").click(function () {
    if (removeClass) {
        $(".button").removeClass('bclose');
    }
    removeClass = true;
});

The "-" & bclose class removes if you click the window or the button again, but if you click one of the other button the "-" doesn't remove.

If i add

$(".button").removeClass('bclose');

it works fine but not if you click the same button again.

Example: http://jsfiddle.net/tjga5/


Solution

  • You can use like this

    $(".button").click(function () {
        $(".button").not(this).removeClass('bclose');
        $(this).toggleClass('bclose');
    
    });
    

    Demo