Click Outside Element To Close (Click On Body To Close)

By September 9, 2017Blog, ES6, Javascript
Allure Web Solutions Code Snippet

With this snippet you can click outside an element specified by a selector to perform some action. A common usage would be to close a popup when clicking outside of the popup.

function hideOnClickOutside(selector) {
  const outsideClickListener = (event) => {
    if (!$(event.target).closest(selector).length) {
      if ($(selector).is(':visible')) {
        $(selector).hide()
        removeClickListener()
      }
    }
  }

  const removeClickListener = () => {
    document.removeEventListener('click', outsideClickListener)
  }

  document.addEventListener('click', outsideClickListener)
}

// Credit: https://stackoverflow.com/a/3028037/3602355

Usage:

hideOnClickOutside('.popup')
Mike Doubintchik

Author Mike Doubintchik

More posts by Mike Doubintchik

Leave a Reply