Handle click outside

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

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • JavaScript Event Handling

    Event handling needs to be done right in JavaScript. Pick up some tips and tricks to create a better user experience.

    Collection · 15 snippets

  • Handle user input change

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

    JavaScript, Browser · Oct 21, 2020

  • Handle scroll stop

    Runs the callback whenever the user has stopped scrolling.

    JavaScript, Browser · Jan 6, 2021

  • Observe element mutations

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

    JavaScript, Browser · Oct 22, 2020