activeElement Restores Focus On Close
Store document.activeElement when a widget opens and restore focus to it on close, so keyboard users return to the trigger instead of the body.
Code
const trigger = document.querySelector<HTMLButtonElement>("#open-menu");
const menu = document.querySelector<HTMLDivElement>("#menu");
const closeBtn = document.querySelector<HTMLButtonElement>("#close-menu");
if (!(trigger && menu && closeBtn)) throw new Error("menu markup missing");
let lastFocused: HTMLElement | null = null;
function openMenu(): void {
lastFocused = document.activeElement instanceof HTMLElement ? document.activeElement : null;
menu.hidden = false;
// 焦点进面板:键盘用户不会落在 body 上
closeBtn.focus();
trigger.setAttribute("aria-expanded", "true");
}
function closeMenu(): void {
menu.hidden = true;
trigger.setAttribute("aria-expanded", "false");
// 关闭时把焦点还给触发按钮(focus restore):activeElement 需收窄成 HTMLElement
if (lastFocused) lastFocused.focus();
lastFocused = null;
}
trigger.addEventListener("click", openMenu);
closeBtn.addEventListener("click", closeMenu);
Inside the snippet
The snippet is organized around the functions openMenu and closeMenu.
Invalid states are rejected up front: it throws Error instead of continuing with bad data.
Caveats
- Entirely standard-library — copy it in and it runs.
- This is browser-side code —
documentwill not resolve in Node.
Putting it to use
Entry signature: function openMenu()
Core lines
if (!(trigger && menu && closeBtn)) throw new Error("menu markup missing");
closeBtn.addEventListener("click", closeMenu);
trigger.addEventListener("click", openMenu);
Interactive Tools for This Topic
WCAG Color Contrast CheckerCalculate WCAG 2.1 color contrast ratios between foreground and background colors. Verify AA and AAA compliance levels for normal and large text accessibility.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Tailwind Color Palette GeneratorGenerate a balanced 50-950 Tailwind CSS custom property color scale from any hex, RGB, or HSL base color with WCAG 2.1 contrast ratios for every stop.
FAQ
- What does the snippet do with malformed data?
- It throws `Error` before any real work runs — handle it at the call site or let it propagate deliberately.
- Does activeElement Restores Focus On Close run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.