Skip to content

Instantly share code, notes, and snippets.

@shchegol
Forked from everdimension/outside_click.js
Last active December 20, 2018 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shchegol/48b1c6bb5eb571c4fe3fb07d7b6ae099 to your computer and use it in GitHub Desktop.
Save shchegol/48b1c6bb5eb571c4fe3fb07d7b6ae099 to your computer and use it in GitHub Desktop.
Listener for clicks outside the element, for example, for closing menus on outside click.
var el = document.getElementById('el');
document.addEventListener('click', outsideEvtListener);
function outsideEvtListener(evt) {
if (evt.target === el || el.contains(evt.target)) {
return;
}
// code handling outside click
// removing the listener to avoid memory leaks
document.removeEventListener('click', outsideEvtListener);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment