TechJunkie is a BOX20 Media Company

Home Mobile Android Close Div or Menu On Click Outside w/ Javascript

Close Div or Menu On Click Outside w/ Javascript

Close Div or Menu On Click Outside w/ Javascript

If you program in Javascript, you’ve probably run across the situation where you want to have menus that open on a click, and that close when the user clicks outside the menu. I’ve developed a pretty simple way to do just that. 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.



Click inside the black box, nothing happens. Click outside, it disappears
$('#showbox').click(function(){ $('#bigbox').show(function(){ document.body.addEventListener('click', boxCloser, false); }); }); function boxCloser(e){ if(e.target.id != 'bigbox'){ document.body.removeEventListener('click', boxCloser, false); $('#bigbox').hide(); } }

Also make sure you include jQuery in your project as some of the functionality above uses that library.

Wedding Wishes and Congratulations

Read Next 

2 thoughts on “Close Div or Menu On Click Outside w/ Javascript”

Vishal says:
Thanks! but dropdown is not working after applying this code.

Is there any other solution?

Israel says:
Is this not possible with pure javascript?

Leave a Reply

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


Will

Nov 22, 2018

57 Articles Published

More