Explain Codes LogoExplain Codes Logo

How do I find out which DOM element has the focus?

javascript
event-listeners
accessibility
focus-management
Anton ShumikhinbyAnton Shumikhin·Aug 31, 2024
TLDR

Get the currently focused DOM element using document.activeElement:

console.log(document.activeElement);

This neat little trick instantly outputs the focused element to the console for your inspection.

Real-time focus watch with event listeners

For real-time focus tracking, you can utilize focus and blur event listeners:

let currentlyFocusedElement; // Listen for focus event document.addEventListener('focus', event => { currentlyFocusedElement = event.target; // You're being watched, element! 👀 }, true); // Listen for blur event document.addEventListener('blur', () => { currentlyFocusedElement = null; // Nothing to see here, carry on! }, true);

This setup captures the current focus state and dynamically updates it at runtime.

Cross-browser considerations

The document.activeElement has wide browser compatibility. However, in Internet Explorer (Yes, it still exists!), document.activeElement can be null before any focus event on the page. Good to know if your target includes dinosaur browsers.

Checking focus state

Ensure that the document is in focus before querying the activeElement, employing document.hasFocus() function:

if (document.hasFocus()) { console.log(document.activeElement); }

It's like knocking before entering a room, right?

For complex interfaces, like tables or forms, augment the user experience by enabling keyboard navigation:

const inputs = document.querySelectorAll('input'); inputs.forEach((input, index) => { input.addEventListener('keydown', e => { if (e.key === "Enter") { e.preventDefault(); // Next stop, subsequent input field. // End of the line? No problem, we loop! inputs[(index + 1) % inputs.length].focus(); } }); });

De-focus using blur()

On a whim to remove the focus from a DOM element programmatically, use blur:

if (document.activeElement) { document.activeElement.blur(); // Look away, nothing to focus here. }

Just be sure activeElement isn't null or document.body, otherwise, things might get blurry.

jQuery equivalent: :focus

If you're more into jQuery, here's a neat equivalent:

var focusedElement = $(document).find(':focus');

But remember kids, jQuery isn’t always faster. Track with care!

No trade-off between speed and accuracy

Accessing document.activeElement is faster than using a querySelector to find focused elements. This is like choosing the high-speed train over walking. 🚄

Null-proofing activeElement

Safeguarding against null when dealing with document.activeElement is a good practice. This will save you from unsolicited surprises.

Beyond the basics

Initialization: Assumptions vs Reality

Never assume the initial focus to be on a specific element at page load. Keep your logic open for any starting point.

Body focus and Unfocus

document.activeElement can return document.body when no active focus or at the start. Not an error, just a default behavior. But don't worry, it's not the body's fault. 😉

You can map out key-press navigation for enhancing usability. Giving the users a little joystick to navigate, if you will.

Active focus: Accessibility's best friend

Active focus management is a cornerstone of accessibility. It's vital to keep focus visible and coherent.