Handle click outside

Angelos Chalaris · JavaScript, Browser, Event · Jan 6, 2021

Runs the callback whenever the user clicks outside of the specified element.

  • Use EventTarget.addEventListener() to listen for 'click' events.
  • Use Node.contains() to check if Event.target is a descendant of element and run callback if not.
const onClickOutside = (element, callback) => {
  document.addEventListener('click', e => {
    if (!element.contains(e.target)) callback();
  });
};
onClickOutside('#my-element', () => console.log('Hello'));
// Will log 'Hello' whenever the user clicks outside of #my-element

Recommended snippets

  • Handle scroll stop

    JavaScript, Browser

    Runs the callback whenever the user has stopped scrolling.

  • Handle user input change

    JavaScript, Browser

    Runs the callback whenever the user input type changes (mouse or touch).

  • Observe element mutations

    JavaScript, Browser

    Creates a new MutationObserver and runs the provided callback for each mutation on the specified element.