Console logging the focused element as it changes

Published on by Hidde de Vries in notes .

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

he 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 & mentions (2)

Chris Heilmann replied: Console logging the focused element as it changes…
Andréia Bohner replied: Just what I'm looking for:

"Console logging the focused element as it changes"
(via @codepo8)…
Leave a comment
Posted a response to this?

This website uses Webmentions. You can manually notify me if you have posted a response, by entering the URL below.