All Topics
Focus Management
Active Element

Active Element

There’s a DOM API that comes in handy for debugging focus: the activeElement API (opens in a new tab). It can be unclear which element is focused in a sequence, and you might need to log out the currently focused element. You can inspect the readonly document.activeElement property from a JavaScript event!

document.body.addEventListener('focusin', () => console.log(document.activeElement));

This snippet will log to the browser console when you Tab through focusable elements on the page. It can surface elements that should be hidden fully but aren’t, or elements you didn’t even realize could receive focus (like a duplicate element for a mobile layout).

You can also watch activeElement in Chrome DevTools by clicking on the eye icon for the expression editor:

activeElement live expression in Chrome DevTools

Another use case includes storing the previously-focused element in a variable when opening a modal, so you can restore focus on close. We’ll do something similar in a later example.

Don’t forget visual focus styles

For any interactive element that a keyboard user can reach, there should be a visual focus outline (opens in a new tab) like a border, underline, or contrasting glow. There are some exceptions, but generally we could use more focus outlines on the web...not less.

There has an unfortunate legacy on the web of reset.css files that included CSS outline: none. You will probably find this the second you start testing with the keyboard. See how many of them you can replace with focus styles through debugging!