Sub topic 6
Making the menu toggle accessible
This chapter assumes you can write the hamburger menu from the previous chapter: a nav element, a button, a list, and a click handler. It also assumes you know what the hidden attribute does and how to read the browser's accessibility tree in dev tools. Here you will find out why that menu can still fail users, and how to fix it.
What the toggle has to communicate
A sighted mouse user sees a three-line icon, clicks it, and sees a list appear. A keyboard user and a screen reader user need the same three facts through other channels:
- Name: what the control is called ("Menu").
- Role: what kind of control it is (a button).
- State and relationship: whether it is open or closed, and which content it controls.
The WCAG success criterion 4.1.2 (Name, Role, Value) requires exactly this. A hamburger menu that uses a div with a click handler has none of it. The browser exposes no role, offers no keyboard focus, and reports no state.
The pattern used here is called a disclosure: a button that shows or hides a block of content. It is not an ARIA menu.
Start with a real button
<button id="menu-toggle" type="button" aria-expanded="false" aria-controls="site-menu">Menu</button>
<nav aria-label="Main">
<ul id="site-menu" hidden>
<li><a href="/products">Products</a></li>
<li><a href="/pricing">Pricing</a></li>
<li><a href="/docs">Docs</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>A native button gives you several things without any code:
- It is in the Tab order.
- It activates on both Enter and Space.
- It exposes the role "button".
- It shows a focus ring.
Replacing it with a div or span means rebuilding all of that by hand, and people often miss one piece. type="button" stops the button from submitting a form if the header ever ends up inside one.
What each attribute does
| Attribute | Purpose | Who it helps |
|---|---|---|
| `aria-expanded="false"` | Reports the open or closed state | Screen reader users hear "Menu, button, collapsed" |
| `aria-controls="site-menu"` | Names the element the button controls | Some assistive technologies can jump to it, but support is uneven |
| `hidden` on the list | Removes the list from view, the accessibility tree, and the Tab order | Everyone, because closed links cannot be focused by accident |
Do not rely on aria-controls alone. Support is inconsistent across screen readers, so aria-expanded is the attribute that carries the meaning.
Keep the name stable
The button's accessible name should not change when its state changes. If the label flips from "Open menu" to "Close menu" and aria-expanded also flips, a screen reader announces something confusing like "Close menu, button, expanded". Choose one approach:
- Keep a fixed name such as "Menu" and let
aria-expandedcarry the state. - Or change the name and omit
aria-expanded.
The first approach is simpler and is the one this chapter uses.
If the button shows only an icon, give it a name with aria-label="Menu", or with visually hidden text inside the button. Mark the icon itself aria-hidden="true" so it is not announced twice. A visible text label such as "Menu" is better still, because many people do not recognize the three-line icon.
Keep state and visibility in sync
The click handler must change aria-expanded and hidden in the same step. If they drift apart, a screen reader says "collapsed" while the list is on screen, or the reverse. The simplest protection is one function that sets both.
const toggle = document.getElementById('menu-toggle');
const menu = document.getElementById('site-menu');
function setOpen(open) {
toggle.setAttribute('aria-expanded', String(open));
menu.hidden = !open;
}
toggle.addEventListener('click', () => {
setOpen(toggle.getAttribute('aria-expanded') !== 'true');
});The state lives in one place, the aria-expanded attribute. The code does not keep a separate JavaScript boolean that could disagree with it.
Keyboard behavior
Because the toggle is a native button, Enter and Space already work. Three behaviors still need code.
Escape closes the menu
Keyboard users expect Escape to dismiss anything that was revealed on demand. When the menu closes, focus must not be lost. If the focused link disappears because its parent became hidden, focus falls back to the document body, and a keyboard user has to Tab from the top of the page again. Returning focus to the toggle puts them back where they started.
The Escape handler in the earlier example always moves focus to the toggle. That is slightly too eager. If a user opens the menu, then clicks into the search field and presses Escape for some other reason, you do not want to pull focus away from the field. Move focus only when it was inside the menu or on the toggle.
Do not move focus on open
A common mistake is to jump focus to the first link when the menu opens. For a disclosure this is not required, and it can disorient users. After activating the button, the next Tab press naturally lands on the first link, because the list follows the button in the DOM. Keep the DOM order the same as the visual order and you get correct focus order for free (WCAG 2.4.3).
Clicking outside and resizing
Closing on an outside click is a convenience for touch and mouse users. Closing when the layout switches to wide matters for consistency. Without it, a user who rotates a tablet with the menu open ends up with aria-expanded="true" on a button that is now display: none.
const toggle = document.getElementById('menu-toggle');
const menu = document.getElementById('site-menu');
const wide = window.matchMedia('(min-width: 48em)');
function setOpen(open) {
toggle.setAttribute('aria-expanded', String(open));
menu.hidden = !open;
}
toggle.addEventListener('click', () => {
setOpen(toggle.getAttribute('aria-expanded') !== 'true');
});
document.addEventListener('keydown', (event) => {
if (event.key !== 'Escape' || menu.hidden) return;
const focusInside =
menu.contains(document.activeElement) || document.activeElement === toggle;
setOpen(false);
if (focusInside) toggle.focus();
});
document.addEventListener('click', (event) => {
if (menu.hidden) return;
if (menu.contains(event.target) || toggle.contains(event.target)) return;
setOpen(false);
});
wide.addEventListener('change', () => setOpen(false));Check the order of the checks. The outside-click handler runs for the toggle's own click too, so it must ignore clicks on the toggle. Otherwise it would close the menu right after the toggle handler opened it.
The `hidden` attribute and CSS
The hidden attribute works because browsers give it a default style, display: none. Any author rule that sets display on the same element beats that default. This is the most common reason a "hidden" menu stays visible:
/* Bug: this overrides the browser's hidden style, so the list is always visible. */
#site-menu {
display: flex;
}On a phone you want the closed list gone, so do not set display on #site-menu outside the wide media query. The CSS from the earlier chapter does this deliberately in reverse. It forces the list to display on wide screens even when hidden is set, because the toggle is gone there and the links must always be reachable:
@media (min-width: 48em) {
#menu-toggle {
display: none;
}
#site-menu,
#site-menu[hidden] {
display: flex;
gap: 1rem;
}
}Animating the open and close
Do not animate by toggling opacity or transform alone and leaving the closed list in place. A list that is invisible but not hidden still receives keyboard focus, and screen readers still read it. If you want a transition, use visibility: hidden in the closed state, which also removes the content from the Tab order and the accessibility tree. Wrap the motion in @media (prefers-reduced-motion: no-preference) so people who asked for less motion do not get it.
When the menu becomes a dialog
A small dropdown below the header is a disclosure. A full-screen overlay that covers the page is a different pattern, closer to a modal dialog, and it has stricter rules:
- Focus must move into the overlay when it opens.
- Focus must not escape to the page behind it. Setting
inerton the main content is the modern way to do this. - Escape must close it, and focus must return to the toggle.
If you build a full-screen menu, treat it as a dialog from the start. Using the native dialog element with showModal() gives you most of this behavior for free.
Do not use `role="menu"`
It is tempting to add role="menu" and role="menuitem" because the pattern is called a "menu". Those roles describe application-style menus, like the File menu in a desktop program. They change how screen readers behave: they switch into a special mode, and users are expected to move with arrow keys. A site navigation list made of ordinary links should stay as nav, ul, and a. Adding the menu roles without the matching arrow-key code makes the navigation harder to use, not easier.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Screen reader says "collapsed" while the list is open | `aria-expanded` and `hidden` updated in different places | Use one `setOpen` function |
| Closed menu is still visible on a phone | An author `display` rule overrides `hidden` | Remove the rule from the narrow layout |
| Links in the closed menu can be focused | The list is hidden with `opacity` or an off-screen transform | Use `hidden` or `visibility: hidden` |
| Keyboard user loses their place after Escape | Focus was on a link that is now hidden | Return focus to the toggle |
| Menu closes immediately after opening | Outside-click handler also catches the toggle click | Ignore clicks inside the toggle |
| Toggle announces "Close menu, expanded" | Label and state both change | Keep a stable label |
| No navigation at all when JavaScript fails | The list is `hidden` in the markup and only script reveals it | Consider setting `hidden` from script on load |
The last row is a real trade-off. Putting hidden in the markup avoids a flash of the open menu on load, but leaves a broken page if the script never runs. Setting it from script is more resilient and causes a brief flash unless the script runs early.
Verify it
Check three things before moving on:
- Keyboard only: Tab to the button, press Enter, Tab through the links, press Escape. Focus must be visibly on the toggle afterward.
- Accessibility tree: In browser dev tools, confirm the button shows role "button", name "Menu", and the correct expanded state.
- Screen reader: Listen to what is announced when you open and close the menu.
The next chapters build on this toggle, and the testing chapter returns to these checks in more detail.
Exercise
A user opens the hamburger menu, tabs to the "Docs" link, and presses Escape. The menu closes, but the next Tab press starts from the top of the page. What went wrong, and what is the fix?
Show answer
The focused link was inside the list that became hidden, so focus was dropped to the document body. The Escape handler must call toggle.focus() after closing the menu, at least when focus was inside the menu or on the toggle.
Exercise
Your CSS has "#site-menu { display: flex; }" outside any media query. On a phone, the menu is visible even though the list has the hidden attribute and aria-expanded is "false". Why, and how do you fix it?
Show answer
An author display rule beats the browser's default display: none for hidden, so the list stays visible. Move the display: flex rule into the wide-screen media query, so the narrow layout leaves the default hidden style in effect.
Exercise
A teammate changes the button text between "Open menu" and "Close menu" and also keeps aria-expanded updated. Why is this a problem, and what is the simplest correction?
Show answer
A screen reader announces both the changed name and the state, for example "Close menu, button, expanded", which is contradictory. Keep a stable name such as "Menu" and let aria-expanded carry the state.