Skip to content
jshacks.dev
Browser

Build a dropdown menu with keyboard support

Build a menu button whose list opens with Enter, moves with the arrow keys, closes on Escape and returns focus to the trigger. Plain JavaScript.

1 min read
Summarize in AI

A dropdown that only works with a mouse is a broken dropdown. The keyboard needs three things: open from the trigger, move through items with the arrows, and close with Escape while returning focus.

menu.jsJavaScript
const trigger = document.querySelector('#menu-trigger');
const menu = document.querySelector('#menu');
const items = [...menu.querySelectorAll('[role="menuitem"]')];

function open() {
  menu.hidden = false;
  trigger.setAttribute('aria-expanded', 'true');
  items[0].focus();
}

function close() {
  menu.hidden = true;
  trigger.setAttribute('aria-expanded', 'false');
  trigger.focus();
}

trigger.addEventListener('click', () => (menu.hidden ? open() : close()));

menu.addEventListener('keydown', (event) => {
  const i = items.indexOf(document.activeElement);
  if (event.key === 'ArrowDown') items[(i + 1) % items.length].focus();
  if (event.key === 'ArrowUp') items[(i - 1 + items.length) % items.length].focus();
  if (event.key === 'Escape') close();
  if (event.key === 'ArrowDown' || event.key === 'ArrowUp') event.preventDefault();
});

The markup is a button with aria-haspopup="menu" and aria-expanded, followed by a ul with role="menu" holding li or button elements with role="menuitem" and tabindex="-1". This follows the menu button pattern. preventDefault on the arrows stops the page scrolling behind the menu.

For site navigation, a plain list of links inside a disclosure button is usually better than role="menu", which promises application-style behaviour.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.