Javascript Detect click event outside of div

Bind the onClick-Event to an element that is outside your content area, e.g. the body. Then, inside the event, check whether the target is the content area or a direct or indirect child of the content area. If not, then alert.

I made a function that checks whether it's a child or not. It returns true if the parent of a node is the searched parent. If not, then it checks whether it actually has a parent. If not, then it returns false. If it has a parent, but it's not the searched one, that it checks whether the parent's parent is the searched parent.

function isChildOf(child, parent) {
    if (child.parentNode === parent) {
      return true;
    } else if (child.parentNode === null) {
      return false;
    } else {
      return isChildOf(child.parentNode, parent);
    }
}

Also check out the Live Example (content-area = gray)!


The Node.contains() method returns a Boolean value indicating whether a node is a descendant of a given node or not

You can catch events using

document.addEventListener("click", clickOutside, false);
function clickOutside(e) {
   const inside = document.getElementById('content-area').contains(e.target);
}

Remember to remove the event listened in the right place

document.removeEventListener("click", clickOutside, false)

I made a simple and small js library to do this for you:

It hijacks the native addEventListener, to create a outclick event and also has a setter on the prototype for .onoutclick

Basic Usage

Using outclick you can register event listeners on DOM elements to detect whether another element that was that element or another element inside it was clicked. The most common use of this is in menus.

var menu = document.getElementById('menu')

menu.onoutclick = function () {
    hide(menu)
}

this can also be done using the addEventListener method

var menu = document.getElementById('menu')

menu.addEventListener('outclick', function (e) {
    hide(menu)
})

Alternatively, you can also use the html attribute outclick to trigger an event. This does not handle dynamic HTML, and we have no plans to add that, yet

<div outclick="someFunc()"></div>

Have fun!


In pure Javascript

Check out this fiddle and see if that's what you're after!

document.getElementById('outer-container').onclick = function(e) {
    if(e.target != document.getElementById('content-area')) {
        document.getElementById('content-area').innerHTML = 'You clicked outside.';          
    } else {
        document.getElementById('content-area').innerHTML = 'Display Contents';   
    }
}

http://jsfiddle.net/DUhP6/2/