How do I hide an element on a click event anywhere outside of the element?

Franek picture Franek · Apr 3, 2009 · Viewed 229.1k times · Source

I would like to know whether this is the correct way of hiding visible elements when clicked anywhere on the page.

$(document).click(function (event) {            
    $('#myDIV:visible').hide();
});

The element (div, span, etc.) shouldn't disappear when a click event occurs within the boundaries of the element.

Answer

Jeremy B. picture Jeremy B. · Apr 3, 2009

If I understand, you want to hide a div when you click anywhere but the div, and if you do click while over the div, then it should NOT close. You can do that with this code:

$(document).click(function() {
    alert("me");
});
$(".myDiv").click(function(e) {
    e.stopPropagation(); // This is the preferred method.
    return false;        // This should not be used unless you do not want
                         // any click events registering inside the div
});

This binds the click to the entire page, but if you click on the div in question, it will cancel the click event.