Skip to content
Advertisement

Close/hide an element when clicking outside of it (but not inside)

I have a <div> that exists on a page and I need to make it so that when the user clicks outside of that element it will become hidden, but if the user clicks somewhere within the element, then it should stay.

I tried using
e.stopPropagation();
and
e.preventDefault();

adding it to the click event of that certain DIV but that didn’t work.

Thanks!

Advertisement

Answer

  • Assign the desired event listener (like "click") to document or window using EventTarget.addEventListener()
  • Use Event.target in combination with Element.closest() as negation ! – in order to check whether the Event.target (the element that initiated the Event) – its self or closest ancestor have a specific selector.
  • To control an element visibility create a CSS class that does the necessary styling, and use Element.classlist to add, remove or toggle that class (as needed).

const elPopup = document.querySelector("#popup");

addEventListener("click", (evt) => {
  if (!evt.target.closest("#popup")) elPopup.classList.remove("isOpen");
});
#popup {
  padding: 2rem;
  background: gold;
  display: none; /* Hidden popup by default */
}

#popup.isOpen {
  display: block;
}
<div id="popup" class="isOpen">
  Click outside to close me.<br>
  Click inside will do nothing.
</div>
  • Never use Event.stopPropagation() unless you really, really know what you’re doing. Your app or third-party code should be always notified about all events happening in their context.

Usage example: Close popup modal on click outside

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement