Console logging the focused element as it changes

When you build a Single Page Application, chances are that you manage some of the focus through script. For debugging, it can be super useful to log the currently focused element to the Dev Tools Console.

Logging the focused element

The focused element is known in the DOM as document.activeElement, so you can just console.log() that if you want to know what the currently focused element is.

Logging it as it changes

Thanks to Eva, I recently learned a way to log the active element as it changes:

document.addEventListener('focusin', function() {
  console.log('focused: ', document.activeElement)
}, true);

The focusin event is like focus, but it bubbles, so when any element within document receives focus, focusin bubbles all the way up to document.

When I posted this on Twitter, Christian Schaefer helpfully pointed out that, although focus does not bubble, it can be intercepted when the capturing flag (addEventListener’s third argument) is set to true. Phil Walton then added that focus fires also for non-interactive elements and when the window receives focus. Even better!

So this is what you could use to log the active element when it changes:

document.addEventListener('focus', function() {
  console.log('focused: ', document.activeElement)
}, true);

Also relevant: PPK’s Delegating the focus and blur events, over 10 years old, in which he explains that lack of bubbling in focus makes sense, because we would not want it to bubble to window, as the `window’ having focus means that the user has focused the entire browser window.

Thanks to Eva on Mozilla Slack for sharing and Christian, Phil and Peter-Paul for further explaining.

Comments, likes & shares (2)

and Jake Archibald liked this

and probably also this one hidde.blog/console-loggin…