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.

TypescriptData Integrity

Code

typescriptsnippet
27 lines
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 — document will 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

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.