delegatesFocus Routes Host Focus Inside

attachShadow with delegatesFocus sends host focus to the first focusable node in the shadow root, and focus events retarget to the host for outside listeners.

TypescriptData Integrity

Code

typescriptsnippet
20 lines
const host = document.querySelector('profile-card') as HTMLElement;
const root = host.attachShadow({ mode: 'open', delegatesFocus: true });

root.innerHTML = `
  <button>Follow</button>
  <input placeholder="search" />
`;

// delegatesFocus: focusing the host pushes focus to the first focusable
// node inside the shadow root instead of needing a tabindex on the host.
host.focus();
console.log('host default tabindex:', host.tabIndex);

host.addEventListener('focusin', () => {
  console.log('focusin seen on host (retargeted from inside shadow)');
});

host.addEventListener('focusout', () => {
  console.log('focusout seen on host');
});

What this snippet actually does — delegatesFocus Routes Host Focus Inside

Demo state sits in top-level bindings: host, root.

What to watch for

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.
  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Putting it to use

These labels appear in the output: host default tabindex:, focusout seen on host — when the file runs.

Core lines

host.addEventListener('focusout', () => {
  console.log('focusout seen on host');
});
host.addEventListener('focusin', () => {
  console.log('focusin seen on host (retargeted from inside shadow)');
});

Interactive Tools for This Topic

FAQ

Does delegatesFocus Routes Host Focus Inside 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.