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.

JavascriptForm Validation

Code

javascriptsnippet
22 lines
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.
  • document exist 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

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.