Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

hide

show

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!

like image 637
BlueCaret Avatar asked Oct 17 '13 06:10

BlueCaret


1 Answers

// 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/

like image 168
LeGEC Avatar answered Nov 05 '22 13:11

LeGEC