FocusEvent.relatedTarget Marks Focus Boundaries

FocusEvent.relatedTarget names the element about to receive focus, letting an open menu tell a genuine move inside the widget from a real focus-out to the page.

JavascriptData Integrity

Code

javascriptsnippet
21 lines
const menu = document.querySelector('.menu');
const trigger = document.querySelector('.menu-trigger');

trigger.addEventListener('focusout', (event) => {
  // relatedTarget is the element focus is moving to, or null when focus
  // leaves the document entirely (clicked browser chrome, alt-tabbed away).
  const next = event.relatedTarget;

  // Close only when focus truly leaves the widget, so tabbing from the
  // trigger into a menu item keeps the menu open.
  if (!next || (!menu.contains(next) && next !== trigger)) {
    menu.hidden = true;
    console.log('menu closed; focus moved to', next ? next.tagName : 'outside');
  } else {
    console.log('menu stays open for', next.tagName);
  }
});

menu.addEventListener('focusin', (event) => {
  console.log('menu item focused:', event.target.tagName);
});

From setup to output — FocusEvent.relatedTarget Marks Focus Boundaries

Demo state sits in top-level bindings: menu, trigger.

Watch out for

  • No third-party code is loaded at any point while this runs.
  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Applying it

Output lines are prefixed (menu closed; focus moved to, menu stays open for, menu item focused:), with the prefix naming the step behind each line.

Statements that matter

menu.addEventListener('focusin', (event) => {
  console.log('menu item focused:', event.target.tagName);
});

Interactive Tools for This Topic

FAQ

Does FocusEvent.relatedTarget Marks Focus Boundaries 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.