Key points
- Attach one click listener to the document, once, rather than a new listener every time the menu opens.
- Use composedPath(): contains() fails when the clicked element has been removed from the page in the meantime.
- An accessible menu also closes on Escape, returns focus to its button and keeps aria-expanded up to date; the popover attribute does this natively.
An account menu, a search filter, a language switcher: they all need to close when you click somewhere else. It’s one of the first things people write in JavaScript, and one of the things we fix most often on sites we take over: a menu that closes the moment it opens, one that never closes on mobile, one that stays open for keyboard users, or ten menus each adding their own listener to the document. Here’s a solid, library-free version, the traps behind the usual bugs, and the native alternative that makes part of this code unnecessary in modern browsers.
HTML that says what it does
It all starts with a real button, not a <div> or an empty link. A <button> can take focus, responds to Enter and Space, and is announced properly by screen readers. aria-expanded says whether the menu is open, aria-controls ties the button to the list, and hidden hides the closed list from sighted users and assistive technology alike:
<div class="dropdown">
<button type="button" class="dropdown-button"
aria-expanded="false" aria-controls="account-menu">
My account
</button>
<ul id="account-menu" class="dropdown-list" hidden>
<li><a href="/account/">Profile</a></li>
<li><a href="/orders/">Orders</a></li>
<li><a href="/logout/">Log out</a></li>
</ul>
</div>
For a menu of links like this one, we don’t add role="menu". That role commits you to arrow-key navigation, which screen reader users will then expect and which you’d have to build entirely yourself. A plain list of links, reached with Tab, is simpler and more robust.
The classic bug: the menu closes as soon as it opens
The version you’ll find most often adds the “click outside” listener at the moment the menu opens:
// Broken version: the menu closes as soon as it opens
button.addEventListener('click', () => {
list.hidden = false;
document.addEventListener('click', e => {
if (!list.contains(e.target)) list.hidden = true;
});
});
It doesn’t work, and the reason is surprising. The click on the button bubbles up through the DOM to the document. A listener added while the event is on its way up gets triggered by that very same click once it reaches the document. The button isn’t inside the list, so the menu closes straight away. And since a new listener is added on every opening and never removed, they pile up.
This bug is often “fixed” with e.stopPropagation() on the button. It works, but it also stops any other code from hearing that click: analytics, other menus, plugin scripts. On a WordPress site with several plugins, that’s the kind of bug that takes hours to connect to its cause.
The right approach is a single listener, attached once, that decides what to do based on where the click landed.
The solid version, for one menu or many
This code handles every menu on the page with one listener. It also works for menus added after page load, for instance in content loaded via AJAX:
function toggle(menu, open) {
menu.querySelector('.dropdown-button').setAttribute('aria-expanded', String(open));
menu.querySelector('.dropdown-list').hidden = !open;
}
function closeAll(except = null) {
document.querySelectorAll('.dropdown').forEach(m => {
if (m !== except) toggle(m, false);
});
}
// A single listener for the whole page, attached once
document.addEventListener('click', e => {
const path = e.composedPath();
const button = path.find(el => el.classList?.contains('dropdown-button'));
const menu = path.find(el => el.classList?.contains('dropdown')) ?? null;
if (button) {
const open = button.getAttribute('aria-expanded') === 'true';
closeAll(menu);
toggle(menu, !open);
return;
}
closeAll(menu); // click elsewhere: close everything except the menu clicked
});
Why composedPath() rather than menu.contains(e.target)? Because the clicked element sometimes disappears before the event reaches the document. The typical case is a “Show more” button inside the menu that replaces its own content, or a component that re-renders. e.target is no longer in the page, contains() returns false, and the menu closes even though the click was inside it. composedPath() returns the path as it was when the click happened, which stays accurate. It also crosses open Shadow DOM boundaries, handy if your page uses web components.
Opening one menu closes the others: two open dropdowns almost always overlap. The state lives in aria-expanded, which acts as the script’s source of truth, as information for screen readers and as a CSS hook, for example to rotate an arrow with [aria-expanded="true"].
Keyboard and mobile: Escape, Tab and touch
A menu that only closes with a mouse is half finished. Two behaviours are expected: Escape closes the menu and returns focus to the button, and tabbing out of the menu closes it.
// Escape: close and give focus back to the button
document.addEventListener('keydown', e => {
if (e.key !== 'Escape') return;
const button = document.querySelector('.dropdown-button[aria-expanded="true"]');
if (!button) return;
toggle(button.closest('.dropdown'), false);
button.focus();
});
// Tabbing out of the menu: close it
document.addEventListener('focusout', e => {
const menu = e.target.closest?.('.dropdown');
if (menu && e.relatedTarget && !menu.contains(e.relatedTarget)) {
toggle(menu, false);
}
});
Returning focus to the button after Escape is essential: without it, focus stays on a link that’s now hidden and keyboard users find themselves “nowhere” on the page. In the focusout listener we only close when relatedTarget, the element receiving focus, is known and outside the menu. Safari doesn’t focus a button when it’s clicked with a mouse, so relatedTarget is null; closing in that case caused a close-then-reopen flicker on one of our projects. Mouse clicks are already handled by the main listener anyway.
On mobile, click fires for a simple tap, iPhones included, since the listener sits on the document. Don’t swap it for touchstart: the menu would close as soon as the user starts scrolling.
The native alternative: the popover attribute
Modern browsers can now do all of this by themselves. With the popover attribute, the element toggles when its button is clicked, closes on outside clicks and on Escape, and automatically closes other open popovers. Not a single line of JavaScript:
<button type="button" popovertarget="account-menu">My account</button>
<ul id="account-menu" popover>
<li><a href="/account/">Profile</a></li>
<li><a href="/orders/">Orders</a></li>
<li><a href="/logout/">Log out</a></li>
</ul>
The element is rendered in a top layer above the page, which also gets rid of z-index and overflow: hidden headaches. The trade-off is positioning: by default the popover shows up in the middle of the screen, not under its button. To line it up you need either CSS anchor positioning (anchor-name and position-anchor), whose support you should check against the browsers you target, or a few lines of JavaScript to work out the position when it opens.
On recent projects we use popover for rich tooltips, filter panels and account menus, and keep the scripted version when a client needs older browsers supported or when the menu is part of the main navigation, where we want full control over the behaviour. Either way, test with a keyboard and a screen reader before shipping.
FAQ
Why use click rather than mousedown or pointerdown?
pointerdown closes the menu slightly sooner, but it also fires when someone starts selecting text or dragging. click represents a completed action, which avoids unwanted closing.
Should the menu close when a link inside it is clicked?
For a link that loads a new page, there’s no need. For a link that acts within the page, such as a filter or an anchor, close it explicitly after the action, or it stays open on top of the content.
Menus, filters, modal dialogs: we build lightweight interfaces that work with a keyboard and are tested on the browsers your customers actually use.



