Using JavaScript’s closest() Method to Capture a “Click outside” an Element

In Practical Use Cases for JavaScript’s closest() Method, Andreas Remdt talks about some nice use cases that use Element.closest().

I especially like this example with a menu. Click on one of the links and it will show the menu which has the class menu-dropdown. Clicking outside said menu will close it. It’s that latter one that leverages Element.closest().

var menu = document.querySelector(".menu-dropdown");

function handleClick(evt) {
  // Only if a click on a dropdown trigger happens, either close or open it.
  …
  
  // If a click happens somewhere outside .menu-dropdown, close it.
  if (!evt.target.closest(".menu-dropdown")) {
    menu.classList.add("is-hidden");
  }
}

window.addEventListener("click", handleClick);

Here’s a pen with the result:

🔥 If you haven’t checked out Hakim El Hattab’s dynamically drawn hit areas for menus, as talked about in Building Better Interfaces, be sure to do so, as they’re amazing:

Published by Bramus!

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.