Experiences on the Front Lines of User Interfaces and Web Development

Detect a click outside a DOM element

It's too bad that Javascript / DOM events do not give you a hook for detecting when there is a click outside of an element. One way you can do this is to listen for clicks on the entire page, then check whether the target was on your element or not. Without the help of jQuery it is hard to get the DOM element that was clicked across all browsers, and still you then have to account for when your control has multiple layers and any one of those elements could have been clicked.

The following approach is much simpler. Listen for clicks on the entire page (using 'html' instead of 'body' since the body may not extend all the way down the page if the content is short). Then, also listen for clicks on your control, and stop the event from bubbling up to the 'html' handler:
// Run the code, such as hide a menu or close a custom control


Source: http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element/153047#153047
comments powered by Disqus