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.
Code
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.
documentexist 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
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.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.