jQuery: hide() box when clicking on body but not() on element itself?
javascript, jquery
Solution
You are capturing a `click` on the `body` which itself is never `#btn` or `#overlay`, and so it does not work as expected. What you need to check against instead is `event.target`
i.e.
$('body').click(function(e) {
var target = $(e.target);
if(!target.is('#btn') && !target.is('#overlay')) {
if ( $('#overlay').is(':visible') ) $('#overlay').hide();
}
});
Problem
I have a `<a href="#" id="btn">Show Box</a>` somwhere in my DOM. Additionally I have a `div#overlay` that is by default set to `display:none;`. ``` // Toggle Overlay $('#btn').click(function(e) { e.preventDefault(); $('#overlay').toggle(); }) $('body').not('#btn, #overlay').click(function() { if ( $('#overlay').is(':visible') ) $('#overlay').hide(); }); ``` Why is this not working? I want the `#btn` to toggle() the overlay when clicking it. However when the overlay is visible and I click anywhere on the document (except the `#btn` itself or the `#overlay`) I want the overlay also to be hidden.