ThiefMaster's approach works but has a small problem to consider if you have multiple places that need to do the same thing. Say you needed to do the same thing with two separate divs, then calling e.stopPropagation() would cause the div1 not to be hidden when clicking div2
Example
div1.addEventListeners('click', function(e){
e.stopPropagation();
}, false);
div2.addEventListener('click', function(e) {
e.stopPropagation();
}, false);
document.body.addEventListener('click', function(e) {
div1.style.display = 'none';
div2.style.display = 'none';
}, false);
Therefore, a safer alternative is (I'll use jQuery for simplicity) http://jsfiddle.net/qzMnj/1/
$(function() {
function hideWhenClickOutside(element) {
$(document).click(function(e){
if ( !element.contains(e.target)) {
$(element).hide();
}
});
}
hideWhenClickOutside(document.getElementById('div1'));
hideWhenClickOutside(document.getElementById('div2'));
})
My point is that calling stopPropagation() can have unwanted side-effects, if you don't have to do it, it's better not to, unless you're sure no-one will ever care about that click.