Sub topic 12
Click, hover, and Escape behavior in mega menus
This chapter covers how a mega menu opens and closes. It assumes you know the disclosure pattern from the earlier chapters: a button with aria-expanded and aria-controls that shows and hides a panel. You should also be comfortable with basic JavaScript event handling and with the hidden attribute.
Why interaction needs its own design
Markup and layout decide what a mega menu contains. Interaction decides whether people can use it. A menu that opens on hover only is unreachable by keyboard and by touch. A menu that never closes traps focus and covers the page. A menu that closes the moment the pointer drifts a few pixels frustrates mouse users.
Three input types must all work:
- Click or tap on the trigger button.
- Keyboard: Enter or Space on the button, Tab to move through links, and Escape to close.
- Hover as an optional convenience for mouse users, never the only way in.
Click is the baseline. Everything else is an addition.
Click: the baseline
Because the trigger is a real button, the browser turns Enter, Space, mouse clicks, and taps into a single click event. You do not need separate key handlers for opening. Listen for click and toggle the state.
Keep two things in sync every time the state changes: the aria-expanded attribute on the button and the hidden property on the panel. If they drift apart, screen reader users hear the wrong state.
const button = document.querySelector('[aria-controls="products-panel"]');
const panel = document.getElementById('products-panel');
function setOpen(open) {
button.setAttribute('aria-expanded', String(open));
panel.hidden = !open;
}
button.addEventListener('click', () => {
setOpen(button.getAttribute('aria-expanded') !== 'true');
});Reading the current state from aria-expanded rather than keeping a separate variable gives you one source of truth.
The panel needs this CSS rule, because display: grid on the panel would otherwise override the hidden attribute:
.mega-panel {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
gap: 1.5rem;
padding: 1.5rem;
}
.mega-panel[hidden] {
display: none;
}Escape: the required exit
Escape must close an open panel. When it does, focus should return to the trigger button. Without that, focus may be on a link that has just become hidden, and keyboard users lose their place on the page.
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && button.getAttribute('aria-expanded') === 'true') {
setOpen(false);
button.focus();
}
});Two details matter here:
- The handler checks that the panel is open first. Otherwise Escape would pull focus to the button every time someone pressed it, even when the menu was closed.
- The listener sits on
document, so Escape works whether focus is on the button or on a link inside the panel.
Hover: an enhancement with risks
Many users expect a mega menu to open when the pointer rests on the trigger. You can support this, but treat it as an extra on top of click. Hover has several failure modes.
| Problem | What happens | Mitigation |
|---|---|---|
| Touch devices | There is no real hover, and browsers emulate it inconsistently | Keep click working; apply hover behavior only where the device supports it |
| Accidental opening | The pointer crosses the menu on the way to something else | Add a short open delay |
| Diagonal travel | The pointer leaves the trigger on its way to the panel and the menu closes | Add a short close delay |
| Hover and click conflict | Hover opens the panel, then the click toggles it closed | Make click open if closed, and avoid closing a panel that hover just opened |
Limiting hover to devices that have it
Use the (hover: hover) media query in JavaScript with matchMedia so touch-only devices skip hover code entirely.
const hoverCapable = window.matchMedia('(hover: hover)');
const wrapper = button.closest('li');
let closeTimer;
function openOnHover() {
clearTimeout(closeTimer);
setOpen(true);
}
function closeOnLeave() {
closeTimer = setTimeout(() => setOpen(false), 250);
}
function bindHover() {
if (!hoverCapable.matches) return;
wrapper.addEventListener('mouseenter', openOnHover);
wrapper.addEventListener('mouseleave', closeOnLeave);
}
bindHover();Binding the events to the wrapping li, which contains both the button and the panel, avoids the gap problem. The pointer moves from the button to the panel without ever leaving the wrapper. The 250 ms close delay covers small gaps and slightly imprecise movement. Because mouseenter cancels the timer, re-entering within that window keeps the panel open.
Do not make hover the only trigger
Hover alone fails keyboard users, switch users, and touch users. The button's click and Escape behavior stays in place regardless. WCAG 1.4.13 (Content on Hover or Focus) also asks that content revealed on hover be dismissible, hoverable, and persistent. Escape handles dismissal. The wrapper binding handles hoverable. The close delay and the requirement that the panel stay open until the user leaves or dismisses it handle persistence.
Closing on outside click and focus leaving
Escape and the button are not the only ways people leave a menu. Two more cases are worth handling.
Click outside. A user who clicks elsewhere on the page expects the panel to close.
document.addEventListener('click', (event) => {
const isOpen = button.getAttribute('aria-expanded') === 'true';
if (isOpen && !wrapper.contains(event.target)) {
setOpen(false);
}
});Focus leaving. A keyboard user who tabs past the last link in the panel moves into the next part of the page, and the panel stays open behind them. Use focusout and check where focus went:
wrapper.addEventListener('focusout', (event) => {
if (!wrapper.contains(event.relatedTarget)) {
setOpen(false);
}
});relatedTarget is the element receiving focus. It is null when focus leaves the window, which also closes the panel. If that is too aggressive for your site, test for null and skip closing in that case.
State of the menu
The behaviors above form a small state machine with two states.
Every transition goes through setOpen. Keeping one function responsible for the change prevents the state and the attribute from disagreeing.
Several menus on one page
Real navigation has more than one mega menu trigger. Opening one should close the others, so two panels never overlap. Generalize the code by looping over every trigger:
const triggers = document.querySelectorAll('nav button[aria-controls]');
function closeAll(except) {
triggers.forEach((trigger) => {
if (trigger === except) return;
trigger.setAttribute('aria-expanded', 'false');
document.getElementById(trigger.getAttribute('aria-controls')).hidden = true;
});
}
triggers.forEach((trigger) => {
const target = document.getElementById(trigger.getAttribute('aria-controls'));
trigger.addEventListener('click', () => {
const willOpen = trigger.getAttribute('aria-expanded') !== 'true';
closeAll(trigger);
trigger.setAttribute('aria-expanded', String(willOpen));
target.hidden = !willOpen;
});
});
document.addEventListener('keydown', (event) => {
if (event.key !== 'Escape') return;
const open = document.querySelector('nav button[aria-expanded="true"]');
if (open) {
closeAll();
open.focus();
}
});Here closeAll() is called with no argument on Escape, so it closes everything. The reference to open is captured before closing, so focus can return to the right button.
Common mistakes
- Using
divoraas the trigger. Adivis not focusable and does not respond to Enter or Space. A link withhref="#"announces as a link but behaves as a button. Usebutton type="button". - Forgetting to update
aria-expanded. The visual state changes but assistive technology still reports "collapsed". - Hiding with
opacityorleft: -9999pxonly. Hidden links stay in the tab order. Use thehiddenattribute ordisplay: none. - Not returning focus on Escape. Focus is lost when the focused element becomes hidden.
- Hover with no delay. The menu flickers and closes on any small movement.
- Trapping focus in the panel. A disclosure panel is not a modal dialog. Tab should flow through it and out the other side.
Quick checklist
- Does Enter or Space on the trigger open and close the panel?
- Does Escape close it and return focus to the trigger?
- Does a click outside the menu close it?
- Does tabbing out of the panel close it?
- Does hover work only as an addition, with a delay, and only on hover-capable devices?
- Does
aria-expandedalways match what is visible?
Exercise
A user opens the Products mega menu with the keyboard, tabs to the second link inside the panel, and presses Escape. The panel closes, but the next Tab keypress jumps to the top of the page. What was missed in the Escape handler, and how do you fix it?
Show answer
The handler closed the panel but did not move focus back to the trigger button. The focused link became hidden, so the browser lost the focus position and restarted from the top of the document. Fix it by calling button.focus() right after setOpen(false), so the next Tab continues from the Products button to the next item in the navigation.
Exercise
Your mega menu opens on mouseenter and closes on mouseleave of the trigger button only, with no delay. Mouse users report that the menu closes before they can reach the links. Give two changes that fix this.
Show answer
First, attach the hover listeners to the wrapper element that contains both the button and the panel, so moving from the button into the panel does not count as leaving. Second, add a short close delay (around 250 ms) using setTimeout, and cancel it with clearTimeout when the pointer re-enters. Optionally, restrict the hover code to devices where matchMedia('(hover: hover)').matches is true.