focusin And focusout Track Focus By Delegation
Listen once on a container because focusin and focusout bubble, so fields added later are tracked without rebinding per-element listeners.
Code
const form = document.querySelector('#wizard');
// focusin/focusout bubble; focus/blur do not — one listener covers the form.
const visited = new Set();
form.addEventListener('focusin', (event) => {
const field = event.target;
visited.add(field.name);
field.closest('.field')?.classList.add('is-active');
console.log('focus in:', field.name);
});
form.addEventListener('focusout', (event) => {
event.target.closest('.field')?.classList.remove('is-active');
console.log('visited so far:', [...visited].join(', '));
});
// Focus events fire from real focus() calls too, not just user clicks.
form.querySelector('#step-name').focus();
form.querySelector('#step-email').focus();
form.querySelector('#step-name').focus();
console.log('completion:', visited.size, 'of', form.querySelectorAll('input').length);Walkthrough of the flow
Top-level bindings form, visited hold the demo state — nothing sits inside a function scope.
What to watch for
- Zero-fetch snippet: every identifier resolves inside the language distribution.
documentexist only in browsers — a Node runtime has no shims for them out of the box.
Putting it to use
The demo output is labeled (focus in:, visited so far:, completion:), so the labels make the output self-explanatory.
Lines that do the work
form.addEventListener('focusout', (event) => {
event.target.closest('.field')?.classList.remove('is-active');
console.log('visited so far:', [...visited].join(', '));
});
form.addEventListener('focusin', (event) => {
const field = event.target;
visited.add(field.name);
field.closest('.field')?.classList.add('is-active');
console.log('focus in:', field.name);
});
const visited = new Set();
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.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.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
FAQ
- Does focusin And focusout Track Focus By Delegation 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.