The most repeated advice about dropdown menu JS is a ten-line snippet. Hide the panel in CSS, add a click listener, toggle a class. It looks right in a demo and comes apart in production, because the moment a div replaces a native control you inherit every part of the contract the browser used to handle for you: keyboard entry, state announcements, focus return, dismissal, touch targets and reflow. The snippet isn’t wrong. It just stops where the hard work starts.
So this isn’t another toggle tutorial. It opens with a gate that decides whether the custom control should exist at all, then gives you markup, wiring and a keyboard contract you can copy, and finishes with a release matrix you can drop straight into a test suite.
Table of Contents
- Choose Between a Native Select and a Custom Dropdown
- Write the Markup and ARIA States First
- How to Wire Open, Close and Dismiss Logic
- Keyboard Interaction and Focus Management
- Make the Menu Work on Touch and Narrow Screens
- Test the Interaction, Then Ship on Zero Critical Failures
Choose Between a Native Select and a Custom Dropdown
For a country field, a delivery slot or a payment type, the native <select> is the better control, and replacing it with a custom JavaScript dropdown is a downgrade you’ll pay for in maintenance and support time. The table below is that argument in one screen.
| Criterion | Native select | Custom JavaScript dropdown |
|---|---|---|
| Semantics | Built-in listbox or select role | Must add roles and labels yourself |
| Keyboard support | Arrow keys, typeahead and Escape built in | Must be coded and tested for every key |
| Screen reader output | Announced correctly by default | Needs aria-expanded, names and state changes |
| Touch targets | Native picker on most mobile browsers | Items must meet minimum target sizes |
| Form submission | Value submitted with the form | Needs a hidden input kept in sync |
| Browser autofill | Supported | Usually not supported |
| Without JavaScript | Works as a plain control | Fails unless the menu degrades to links |
| Maintenance burden | Low | High, including regression testing across browsers |
Build the custom control only when the interaction is menu-like: header navigation made of links, a command menu of actions, or a picker a design system insists on for something richer than a plain choice. Take a checkout apart and the split is obvious. The country field stays a <select>. The header Products menu, with grouped category links and an “All products” link at the bottom, becomes a disclosure button.
Three questions settle it before any code gets written.
- Does the control need links or commands? If the items open links or trigger actions rather than set a value, a select can’t do it.
- Does it need a layout a select cannot show? Grouped columns, icons, badges or product thumbnails won’t live inside a native list.
- Can a native control do the job? If yes, ship it. Two “no” answers mean you build.
For UK public sector services the bar is statutory as well as practical: sites and apps must meet WCAG 2.2 AA and publish an accessibility statement, as set out in the UK government accessibility requirements for public sector websites and apps. That’s what makes keyboard and focus behaviour a requirement rather than polish. When the answer is the native control, start from a native select field that keeps the browser’s own behaviour intact.
Write the Markup and ARIA States First
Start with a <button>, not a div with a click handler. A button lands in the tab order, takes focus and fires on Enter and Space before you write any JavaScript. A div needs tabindex, a keydown handler and a role before it imitates the same thing, and it still behaves differently under speech recognition.
Here’s the component in three pieces of markup, before any script exists.
- The trigger:
<button type="button" aria-expanded="false" aria-controls="products-menu">Products</button>. - The panel:
<div id="products-menu" hidden>wrapping a<ul>of three<a href>links. - The links: real anchors with visible text, so the menu still works if the script never arrives.
Each attribute earns its place. aria-expanded is the open or closed state a screen reader announces; without it a user hears “Products, button” and has no way to tell whether the menu is showing. aria-controls points assistive technology at the panel by id, which some screen readers use to jump straight to the content. The hidden attribute is the part most snippets get wrong. It removes the panel from both the tab order and the accessibility tree in one move, so collapsed links can’t be tabbed into by accident.
The markup goes into the design before the code does.

Disclosure or menu role
For site navigation, build a disclosure with links inside. Screen readers already announce links well, and Tab moves into the open panel the way people expect. Reserve role="menu" with menuitem children for application-style command lists, because that role promises arrow-key navigation and a specific announcement pattern, and you’re then responsible for building every part of it yourself.
Don’t hang aria-haspopup on a navigation disclosure. It advertises a different widget and leaves users pressing keys that do nothing. Name the trigger after the panel (Products, not Menu), give every item visible text, and keep the links in the HTML so the script only decides whether the panel shows.
At least 1 in 5 people in the UK report having a disability, according to the GOV.UK Design System accessibility strategy, which also asks services to work without JavaScript and treat it as an enhancement layered on top of a working page. That’s the standard the markup above is written to. If the role choices still feel murky, the ARIA roles reference sets out what each role promises before you commit to one.
How to Wire Open, Close and Dismiss Logic
Keep the controller small: four listeners and one shared state update function. State drift leaves aria-expanded announcing one thing while the panel shows another, so write the attribute and visibility together. Every opening and dismissal path should call that same function.
These six moves cover the controller.

- Cache the trigger and the panel once. Query them during setup and retain the wrapper reference too. Keep those references together so every handler checks the same widget, especially on pages with several dropdowns.
- Flip state on the trigger click. Read
aria-expanded, compare it to'true', and pass the opposite boolean to your state function. That function writesString(open)withsetAttributeand setspanel.hidden = !open. Dismissal handlers should explicitly close, never toggle. - Write the string on every change, including on load. Call the same function during setup to establish the initial state. Starting with
aria-expanded="false"while the panel remains visible gives screen reader users an announcement that contradicts the page. - Close on an outside pointerdown. Listen for
pointerdownon the document and checkwrapper.contains(event.target). Close only when the target is outside. This event runs before focus moves and beforeclick; the containment check keeps a trigger press from being treated as an outside dismissal. - Close on Escape and return focus first. In the wrapper’s
keydownhandler, checkevent.key === 'Escape'and whether the panel is open. Focus the trigger before hiding the panel so focus does not remain inside hidden content. Keep this focus return specific to Escape, rather than stealing focus after an outside press. - Close when focus leaves the widget. Handle
focusoutand check whetherevent.relatedTargetis inside the wrapper. Keep the panel open for movement within the widget. Treat a null target as outside and close, including when focus moves to browser chrome.
The portalled panel problem: rendering the panel into
document.bodyto escapeoverflow: hiddenbreaks a wrapper-only containment check. A press inside the panel then looks like an outside press. Keep the panel inside the wrapper or check both nodes for pointer and focus dismissal.
Hover should remain optional. Use click and keyboard opening as the primary paths, with hover only as a desktop extra behind (pointer: fine). Hover-only opening leaves touch and keyboard users without an entry point.
In a single-page app, pair document-listener registration with cleanup when the widget unmounts. Repeated registration across renders or route changes leaves multiple handlers controlling the same panel.
The walkthrough below shows the wiring being assembled.
Keyboard Interaction and Focus Management
The full contract for a disclosure with links fits in one table. Anything not on this list is a bonus.
| Key | On the trigger | Inside the open panel |
|---|---|---|
| Enter or Space | Opens the panel and keeps focus on the trigger, or moves it to the first link | Activates the focused link |
| ArrowDown | Opens the panel and moves focus to the first link | Moves focus to the next item |
| ArrowUp | Opens the panel and moves focus to the last link | Moves focus to the previous item |
| Home or End | No change | Moves focus to the first or last item |
| Escape | Closes the panel if open | Closes the panel and returns focus to the trigger |
| Tab | Moves focus into the open panel | Moves focus to the next control and closes the panel |
| Shift+Tab | Moves focus to the previous control | Returns focus to the trigger and keeps the panel open until focus leaves |
Two focus models sit behind that table. For a disclosure of links, let focus stay on the trigger and let Tab walk into the open panel. It’s simpler, it matches how people already browse, and it needs no extra code. For a command menu driven by arrow keys, use a roving tabindex: set every item to -1, give the active item 0, and move that value as the arrows move the highlight.
The UK Government Digital Service’s accessibility monitoring of public sector websites and mobile apps from 2022 to 2024 recorded 29,787 accessibility issues across the services it monitored, of which 16,482, or 55.3%, were fixed in that window. Navigation dropdowns appear in it as a recurring risk: menus that can’t be expanded by keyboard, or where users tab through links while the menu is visually minimised and focus becomes invisible. Both failures are ordinary markup bugs, not edge cases.
The rules that keep focus predictable
- Never remove an outline without a replacement. A
outline: nonewith no substitute leaves keyboard users stranded. Use:focus-visiblewith a clear offset ring so a mouse click stays quiet while a Tab press is loud. - Closed means gone. A collapsed panel must be out of the tab order. If you animate height instead of using
hidden, setvisibility: hiddenandpointer-events: noneat the end of the transition. - Tab out of the last item, don’t trap. A disclosure isn’t a modal. Tabbing from the final link should close the panel and carry on down the page.
- Nested menus get two extra keys. ArrowRight opens a submenu and moves focus into it, ArrowLeft or Escape returns focus to the parent row.
The keydown handler in four moves
- Map
event.keythrough a key map object. One lookup routes ArrowDown, ArrowUp, Home, End and Escape to named functions, which keeps the handler readable and the branches testable. - Build the items array once. Use
querySelectorAllat setup, keep acurrentIndex, and callpreventDefault()beforeitems[currentIndex].focus()so the page doesn’t scroll under the highlight. - Move the tabindex with the highlight. Set
-1on every item and0on the active one on each move, so the browser’s own focus order agrees with the visual one. - Run the same movement from the trigger. ArrowDown on the button opens the panel and lands focus on the first item, which is the behaviour people try first.
If the panel is a disclosure of links, skip roving tabindex entirely. Tab does the work and there’s nothing to keep in sync.
Make the Menu Work on Touch and Narrow Screens
A panel that’s 320 CSS pixels wide with 24 pixel rows is fine with a trackpad and unusable with a thumb. Six changes make the same component work on a phone.
- Give every item a 44 by 44 CSS pixel target with 8 pixels between items. That’s the practical floor for a fingertip, and spacing matters as much as size because adjacent rows get hit by the same thumb.
- Open on click or tap, never on hover alone. Add hover opening behind a
(pointer: fine)query as a desktop nicety. Touch, keyboard and switch access all go through the click path. - Below 480 pixels, let the panel become a full-width sheet. Fix it to the viewport, give it
overflow-y: autoand amax-heightof100dvhminus the trigger height, so a long list of category links scrolls instead of clipping off the screen. - Set
inerton the rest of the page while that sheet is open, and lock body scroll withoverflow: hidden. Remove both on close, in afinallyblock if the close path can throw, or a failed close leaves the page frozen. - Re-check placement for inline menus. Position the panel absolutely inside a relatively positioned wrapper, and flip it above the trigger when there’s no room below. Recalculate on
scrollandresize, debounced, or the panel detaches from its trigger. - Wrap the open and close transitions in a
prefers-reduced-motioncheck. Slide and fade are decoration; the state change is the function.
Testing on a laptop at 1440 pixels hides all of this. Why laptop-only testing misses mobile users makes the case for putting a real device in the loop before launch, and the two things a device catches fastest are the 320 pixel reflow and a focus ring that vanishes against a coloured header.
Test the Interaction, Then Ship on Zero Critical Failures
Release gates work when they treat a dropdown as a contract, not a decoration. The contract says what opens, what closes, where focus goes, what assistive technology hears, and what still works at 320 CSS pixels. If one of those promises breaks, the control is shipped broken, even when the visual design looks finished.
The parliamentary written answer on accessibility monitoring reports 1,203 websites and 21 mobile applications monitored between January 2022 and September 2024 with automated and manual checks, including keyboard testing. The same results show that 77.3% of websites had a minimum contrast issue and 55.4% had a reflow issue. Those are the failure modes that survive a clean component demo: the focus ring disappears into a coloured header, the panel clips on a narrow screen, or the keyboard path lands somewhere the user did not expect.

| Check | How to run it | Pass condition |
|---|---|---|
| aria-expanded state | Activate the trigger with the keyboard | Reads true while open and false when closed |
| Panel exposure | Inspect the DOM and the accessibility tree | Closed panel is hidden from both the tab order and the accessibility tree |
| Escape restores focus | Open the menu, press Escape | Focus lands on the trigger |
| Accessible names | Check each link or item in the accessibility tree | Every actionable item has a name |
| Focus visibility | Tab through the widget | Focus indicator is visible against its background |
| Reflow at narrow width | View at 320 CSS pixels | No items are clipped or unreachable |
| Text scaling | Set browser text to 200% | Panel remains usable without horizontal scrolling |
| Outside click and blur | Click outside and tab out | Panel closes without navigating |
Automated scanners catch part of that contract. They can flag a missing accessible name and a state that never changes. They cannot prove that focus returns to the right trigger after Escape, that tab order still matches the visual order, or that a submenu does not trap keyboard users. The GOV.UK service manual guidance on making your service accessible asks services to work with commonly used assistive technologies, including screen magnifiers, screen readers and speech recognition tools, so budget one manual pass per major browser with a real screen reader before launch. Ten minutes with VoiceOver and one keyboard is worth more than a clean report.
Practical rule: a missing focus indicator is a critical failure, not a cosmetic one. Gate the release on zero of those and let everything else queue behind it.
Two interaction behaviours get the pattern rejected most often: attaching navigation to a focus event, and changing the page while a user is merely tabbing between options. Both break the basic promise that moving focus is a navigation act for the reader, not for the site. Focus should prepare the next action. Activation should perform it.
Use component testing to turn the eight rows above into repeatable assertions. Run them at the viewport sizes and input modes the product supports: pointer, keyboard, touch and a narrow screen. Keep the matrix small enough that a failed build gives a precise answer. “Escape restores focus” fails differently from “panel exposure”, and each points to a different fix.
If several menus share the same pattern, a headless primitive that already handles roving focus saves the rebuild. DOM Studio’s Vue Menu Component is a roving-focus action menu for command lists, settings panels and skinned menus. Its menu skin renders with the floating skin and should be disabled when the menu is embedded inside a popover or dropdown. That keeps the product-specific behaviour in your code while the keyboard contract stays consistent.
