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')