Close Div or Menu On Click Outside w/ Javascript

javascript code

If you’ve ever dealt with menus that open on click, but want them to close when a user clicks outside the menu area, here’s a pretty simple way to do it. I add an event listener to the document’s body.  When someone clicks it, we look for the event’s target id.  If it matches the ID of the box’s div, then do nothing.  If it doesn’t, close the menu.

Taking that a little further, it is inefficient to leave a click event listener on the entire body when it is not being used.  In this case, if the menu hasn’t been opened yet, there’s no reason to listen for a click outside of the menu.  Add the event listener in the callback of the div being shown.  In that same vein, when the div is being hidden again, remove the event listener.

  <a href="#" id="showbox">Show Div</a>

<div style="width:500px; height:200px; background-color: #000; color: #fff; display: none;" id="bigbox">
  Click inside the black box, nothing happens. Click outside, it disappears
<script type="text/javascript">


    document.body.addEventListener('click', boxCloser, false);


function boxCloser(e){
  if( != 'bigbox'){
     document.body.removeEventListener('click', boxCloser, false);


See working example

Also make sure you include jQuery as some of the functionality above uses the library.

Posted by Will on March 5, 2014

Leave a Reply

Your email address will not be published. Required fields are marked *

TechJunkie Also Recommends