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.
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.
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.