In a recent project, I had to deal with this task – writing and event handler to detect click events outside an element.  The first thing that came to mind was listening for click events somewhere higher in the DOM hierarchy ( can be parent element, or the window object for example ). Then, I can determine the element that triggered the event and all the elements, through the event bubble .

Here is the final result:

See the Pen Click outside element by Chrysto (@burnandbass) on CodePen


Let’s take a look of the code. I cache the div and the window object in variables named $box and $win. Then, I use namespaced event to listen for click events on the document window. Once a click event occur I determine if the event originated from the box ( the element is event.target ) , and also did the event bubbled trough the element ( the element has been in the event bubbling ). The second verification ensures that you will catch the the events that was triggered by element descendants. Here is the final code:


var $win = $(window); // or $some parent container to narrow the area
var $box = $(".box");
				
$win.on("click.Bst", function(event){		
   if ( $box.has(event.target).length == 0 && !$box.is(event.target) ){
         //you clicked outside the element - the $box is not the target and the event was not triggered by $box descendants
   }
});