Jquery - Add class on click of button / Remove class on click of body

BlueCaret picture BlueCaret · Oct 17, 2013 · Viewed 19.8k times · Source

I have a div that I want to show when a button is clicked, and then if anywhere else on the page (including the original button) except for that hidden div is clicked then I want the div to hide again.

I think I'm pretty close, just can't get it right. This is what I have so far (as a basic example:

$(".clickme").click(function () {
    $(".toggletag").addClass('open');
});
if ( $('.toggletag').hasClass('open') ) {
    $("html").click(function () {
        $(".toggletag").removeClass('open');
    });
}

Here is a JSfiddle using this code: http://jsfiddle.net/vgf6g/1/

I tried without the if statement at first but that of course caused the html click to override the button click causing the div to never show.

Thanks!

Answer

LeGEC picture LeGEC · Oct 17, 2013
// flag : says "remove class when click reaches background"
var removeClass = true;

// when clicking the button : toggle the class, tell the background to leave it as is
$(".clickme").click(function () {
    $(".toggletag").toggleClass('open');
    removeClass = false;
});

// when clicking the div : never remove the class
$(".toggletag").click(function() {
    removeClass = false;
});

// when click event reaches "html" : remove class if needed, and reset flag
$("html").click(function () {
    if (removeClass) {
        $(".toggletag").removeClass('open');
    }
    removeClass = true;
});

http://jsfiddle.net/vgf6g/3/