Detect clicks outside of specific div and all of it's children
You're on the right way and only need one little change inside your code. Instead of only checking if the event.target is the same as the div, also check if the div contains the event target:
var container = document.getElementsByClassName('container')[0];
document.addEventListener('click', function( event ) {
if (container !== event.target && !container.contains(event.target)) {
console.log('clicking outside the div');
}
});
If for some reason HTMLnode.contains() is not supported (safari, im looking at you), you can use following snippet to check if an element contains another:
function childOf( node, ancestor ) {
var child = node;
while (child !== null) {
if (child === ancestor) return true;
child = child.parentNode;
}
return false;
}