Sub topic 12
Add a mobile menu toggle button
This chapter finishes the navigation bar. On narrow screens the bar collapses behind a button. You will build that button, wire it to the list, and handle the edge cases that usually break it.
Prerequisites
This chapter assumes you have the bar from the earlier chapters:
- A
navelement holding aulwith the idnav-list. - Flexbox on
.nav-list, with the link, hover, focus andaria-currentstyles. - Basic JavaScript: selecting elements, adding event listeners, and toggling classes.
You also need the media query from the previous chapter. That chapter stacked the links in a column below a breakpoint. This chapter adds the control that opens and closes the stacked list.
Why the bar needs a toggle
A row of four or five links does not fit on a phone. Stacking them in a column fixes the width, but the column pushes the page content below the fold. The usual answer is to hide the list on small screens and show a button that reveals it.
The button has three jobs:
- Show and hide the list visually.
- Tell assistive technology whether the list is open or closed.
- Work from the keyboard, as any other control does.
A native button element gives you the keyboard behavior without extra work. It is focusable and it fires click on Enter and Space.
The markup
Place the button inside the nav, before the list:
<button class="nav-toggle" aria-expanded="false" aria-controls="nav-list">Menu</button>Each part has a purpose:
| Part | Purpose |
|---|---|
| `<button>` | Gives keyboard focus and Enter/Space activation for free. A `div` or `span` does not. |
| `aria-expanded="false"` | Tells a screen reader the controlled content is collapsed. Script flips it to `"true"` when the menu opens. |
| `aria-controls="nav-list"` | Names the element the button controls. It must match the list's `id`. |
| Text `Menu` | The visible label, which is also the accessible name. |
Keep the visible text and the accessible name the same. If you add an aria-label such as "Open navigation" to a button that shows "Menu", people who use voice control and say "click Menu" may fail to activate it. If you use an icon-only button, put an aria-label on it and avoid changing the label when the state changes. Let aria-expanded report the state.
In a form, a button defaults to type="submit". The nav is not in a form, so this does not matter here. If you reuse the component inside a form, add type="button".
The CSS: show the button only on small screens
The button is hidden by default. Inside the media query, it appears and the list collapses:
.nav-toggle {
display: none;
}
@media (max-width: 40rem) {
.nav-toggle {
display: block;
}
.nav-list {
display: none;
flex-direction: column;
}
.nav-list.is-open {
display: flex;
}
}The rules work in layers:
- Outside the media query,
.nav-liststaysdisplay: flexfrom the layout chapter, and the button isdisplay: none. Wide screens never see the toggle. - Inside the media query,
.nav-listbecomesdisplay: none. The.is-openrule has higher specificity because it combines two classes, so it overrides that rule and brings the list back as a flex column. display: noneremoves the list from both the visual page and the accessibility tree. Its links also leave the tab order. A closed menu therefore cannot trap keyboard focus on invisible links. Do not hide the menu withopacity: 0or by moving it off-screen unless you also handle focus. Those techniques leave the links tabbable.
A rem in a media query is relative to the browser's default font size, not to your CSS. With the default of 16px, 40rem is 640px. If a user raises the default size, the breakpoint moves with it, which suits a layout that must fit larger text.
Make sure the page has this tag in the head. Without it, phones pretend to be about 980px wide and your media query never matches:
<meta name="viewport" content="width=device-width, initial-scale=1">Style the button
Give the button the same visual language as the links. Browsers apply their own button appearance, so reset the parts you want to control:
.nav-toggle {
display: none;
width: 100%;
padding: 0.75rem 1rem;
border: 0;
background: #1f2937;
color: #ffffff;
font: inherit;
text-align: left;
cursor: pointer;
}
.nav-toggle:hover,
.nav-toggle:focus-visible {
background: #374151;
}
.nav-toggle:focus-visible {
outline: 2px solid #38bdf8;
outline-offset: -2px;
}Notice that .nav-toggle is declared once with display: none. This block replaces the earlier two-line rule. Keep one declaration so the base state is easy to find. The focus rule is the same one the links use, so keyboard users see a consistent ring.
The JavaScript: keep two states in sync
The visual state is the is-open class. The announced state is aria-expanded. If they disagree, a screen reader user hears "collapsed" while the menu is on screen. The script updates both in one place.
const toggle = document.querySelector('.nav-toggle');
const list = document.getElementById('nav-list');
toggle.addEventListener('click', () => {
const isOpen = toggle.getAttribute('aria-expanded') === 'true';
toggle.setAttribute('aria-expanded', String(!isOpen));
list.classList.toggle('is-open', !isOpen);
});Two details matter here:
getAttributereturns a string. Comparing it to'true'converts it to a boolean. Writingif (toggle.getAttribute('aria-expanded'))would be a bug, because the string'false'is truthy.classList.toggle('is-open', !isOpen)passes a second argument that forces the class on or off. Callingtogglewith no second argument flips the class blindly. If the class and the attribute ever drifted apart, they would stay apart.
Common edge cases
The short script works, but a few situations need extra care.
Escape closes the menu
Users expect Escape to close an open menu. After closing, move focus back to the button so a keyboard user does not lose their place. Refactor the script around one setOpen function so every path updates both states:
const toggle = document.querySelector('.nav-toggle');
const list = document.getElementById('nav-list');
function setOpen(open) {
toggle.setAttribute('aria-expanded', String(open));
list.classList.toggle('is-open', open);
}
toggle.addEventListener('click', () => {
setOpen(toggle.getAttribute('aria-expanded') !== 'true');
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && toggle.getAttribute('aria-expanded') === 'true') {
setOpen(false);
toggle.focus();
}
});Resizing the window
Suppose a user opens the menu on a narrow window, then widens it. The button disappears, but aria-expanded is still "true" and is-open is still set. Shrink the window again and the menu appears already open. Reset the state when the breakpoint is crossed:
const query = window.matchMedia('(max-width: 40rem)');
query.addEventListener('change', () => {
setOpen(false);
});Add this after setOpen is defined. The query string must match the one in your CSS. If you change the breakpoint in one place, change it in the other.
JavaScript fails or is disabled
If the script does not run, the button does nothing and the media query hides the list. On a phone, the user then has no navigation at all. Two fixes are common:
- Mark the page as script-capable and scope the hiding rule to it. Put
document.documentElement.classList.add('js');in a small script in thehead, then write.js .nav-list { display: none; }inside the media query. Without thejsclass, the stacked list stays visible. - Keep the primary links also available in the footer.
The first fix is a cheap way to keep the bar usable if the script fails. The cost is one more selector to maintain.
Submenus on a touch screen
The dropdown from the earlier chapter uses position: absolute, which makes the submenu float over the content below it. In a stacked mobile list, that overlap looks wrong and covers other links. Inside the media query, put the submenu back into the normal flow:
@media (max-width: 40rem) {
.submenu {
position: static;
padding-left: 1rem;
}
}The :hover and :focus-within rules still reveal it. Touch devices have no true hover, so a tap on the parent link may trigger hover and navigation at once. A more reliable pattern is a second toggle button for each submenu, built the same way as this one.
Sticky bar plus open menu
The bar is position: sticky from an earlier chapter. An open menu makes the bar taller, and on a short phone screen the list can be taller than the viewport. Part of the menu then cannot be reached while the bar is stuck. Cap its height and let it scroll:
@media (max-width: 40rem) {
.nav-list.is-open {
max-height: calc(100vh - 3rem);
overflow-y: auto;
}
}Adjust 3rem to the height of your button.
A complete page
This file combines the pieces. Save it as an .html file and open it in a browser. Narrow the window below 640px to see the toggle.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Navigation toggle demo</title>
<style>
body { margin: 0; font-family: sans-serif; }
nav {
position: sticky;
top: 0;
z-index: 10;
background: #1f2937;
}
.nav-list {
display: flex;
gap: 0.25rem;
margin: 0;
padding: 0;
list-style: none;
}
.nav-list a {
display: block;
padding: 0.75rem 1rem;
color: #ffffff;
text-decoration: none;
}
.nav-list a:hover,
.nav-list a:focus-visible,
.nav-toggle:hover,
.nav-toggle:focus-visible {
background: #374151;
}
.nav-list a:focus-visible,
.nav-toggle:focus-visible {
outline: 2px solid #38bdf8;
outline-offset: -2px;
}
.nav-list a[aria-current="page"] {
background: #111827;
border-bottom: 3px solid #38bdf8;
}
.nav-toggle {
display: none;
width: 100%;
padding: 0.75rem 1rem;
border: 0;
background: #1f2937;
color: #ffffff;
font: inherit;
text-align: left;
cursor: pointer;
}
@media (max-width: 40rem) {
.nav-toggle { display: block; }
.nav-list {
display: none;
flex-direction: column;
}
.nav-list.is-open {
display: flex;
max-height: calc(100vh - 3rem);
overflow-y: auto;
}
}
main { padding: 1rem; height: 150vh; }
</style>
</head>
<body>
<nav aria-label="Main">
<button class="nav-toggle" aria-expanded="false" aria-controls="nav-list">Menu</button>
<ul class="nav-list" id="nav-list">
<li><a href="/" aria-current="page">Home</a></li>
<li><a href="/products">Products</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
<main>
<h1>Page content</h1>
<p>Scroll to check that the bar stays at the top.</p>
</main>
<script>
const toggle = document.querySelector('.nav-toggle');
const list = document.getElementById('nav-list');
const query = window.matchMedia('(max-width: 40rem)');
function setOpen(open) {
toggle.setAttribute('aria-expanded', String(open));
list.classList.toggle('is-open', open);
}
toggle.addEventListener('click', () => {
setOpen(toggle.getAttribute('aria-expanded') !== 'true');
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && toggle.getAttribute('aria-expanded') === 'true') {
setOpen(false);
toggle.focus();
}
});
query.addEventListener('change', () => setOpen(false));
</script>
</body>
</html>The script sits at the end of body, after the elements it selects. If you place it in the head, add the defer attribute and load it from a file, or querySelector returns null.
Summary of decisions
| Decision | Choice | Reason |
|---|---|---|
| Control element | `button` | Keyboard support is built in. |
| State exposed to assistive technology | `aria-expanded` | Announces open or closed. |
| Hiding method | `display: none` | Removes links from the tab order too. |
| Class and attribute updates | One `setOpen` function | They cannot drift apart. |
| Breakpoint | Same value in CSS and `matchMedia` | The reset fires at the right width. |
Exercise
A user opens the menu at 500px width, then rotates the device so the viewport becomes 900px wide, and rotates back. Without the matchMedia reset, what do they see after rotating back, and what does a screen reader announce? Which line of code fixes it?
Show answer
The menu is already open after rotating back, because the is-open class was never removed. The screen reader announces the button as expanded, because aria-expanded is still "true". The fix is query.addEventListener('change', () => setOpen(false));, which closes the menu and resets both the class and the attribute whenever the viewport crosses the breakpoint.
Exercise
A teammate writes if (toggle.getAttribute('aria-expanded')) { close(); } else { open(); }. Why does the menu never open, and how do you fix the condition?
Show answer
getAttribute returns a string, and the string "false" is truthy in JavaScript, so the condition is always true and the code always calls close(). Compare the string explicitly: toggle.getAttribute('aria-expanded') === 'true'.
Exercise
Add a rule so that on screens under 40rem, the toggle button shows "Menu" on the left and nothing else changes, and explain why you would not hide the closed list with opacity: 0.
Show answer
The button already has text-align: left and width: 100% in the .nav-toggle rule, so no new rule is needed. The point of the second half: opacity: 0 hides the list visually but leaves its links in the tab order and the accessibility tree, so keyboard users would tab onto invisible links. display: none removes them from both.