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:
Started drawing dynamic SVG hit areas for this menu component 👀 pic.twitter.com/tKqwN5F6rW
— Hakim El Hattab (@hakimel) May 27, 2019