JQuery - add a class when a button is clicked / delete a class when clicked

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

I think I'm pretty close, just can't understand. This is what I still have (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 an if statement first, but that of course made html click to override the button click, causing the div to never show.

Thanks!

+7
jquery hide show
source share
4 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/

+5
source share

I think this does what you want:

http://jsfiddle.net/ch94M/2/

 $(".clickme").click(function (e) { $('.toggletag').toggleClass('open'); e.stopPropagation() }); $(document).click(function (e) { if (! $(e.target).hasClass('toggletag')) $(".toggletag").removeClass('open'); }); 
  • If you click the button first, a div will appear on it. If you click it again, it is hiding.

  • If you click on a hidden div that is now viewable, it does not hide.

  • If you click in another place that it hides.

+3
source share

It works:

 $(document).click(function (e) { $el = $(e.target); if ($el.hasClass('toggletag')) {return false;} else if($el.hasClass('clickme')) { $(".toggletag").toggleClass('open'); } else { $(".toggletag").removeClass('open'); } }); 

Demo here

+2
source share

how

 $(".clickme").click(function (e) { e.stopPropagation(); $(".toggletag").toggleClass('open'); }); $(document).click(function (e) { if(!$(e.target).closest('.toggletag').length){ $(".toggletag").removeClass('open'); } }); 

Demo: Fiddle

+1
source share

All Articles