How to close/hide a DIV element when clicking outside of it (but not inside)
I have a <div>
that exists on a page and I need to make it so that when the user clicks outside of that element it will become hidden, but if the user clicks somewhere within the element, then it should stay.
I tried usinge.stopPropagation();
ande.preventDefault();
adding it to the click event of that certain DIV but that didn't work.
Thanks!
Solution 1:
Toggle a flag on popup hover:
JSBin demo
var $pop = $('#popup'),
notHov = 1; // Hover flag
$pop.hover(function(){ notHov^=1; }); // Toggle flag on hover
$(document).on('mouseup keyup', function( e ){
if(notHov||e.which==27) $pop.fadeOut();
});
Note:
if somewhere on the page you have an element the prevents the mouseup event
to bubble up the DOM tree reaching document
(in order to be registered), you might want to create a full-screen (like an page-overlay) popup wrapper to register the click events, changing in the code above just the selector: instead of $(document)
would be $('#popupWrapper')
Solution 2:
Probably the easiest way to do this will be to monitor clicks on the entire document, and ignore it if it's not that element. If it is, then hide it.
(function(div) {
$(document).click(function(e) {
if (e.srcElement !== div) $(div).hide();
});
})($('div')[0]);
Edit: Derp, misunderstood, click inside should stay, otherwise hide... invert the equality check.
http://jsfiddle.net/robert/QcPx4/