How do I find out which DOM element has the focus?
Get the currently focused DOM element using 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:
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:
It's like knocking before entering a room, right?
Navigating complex interfaces
For complex interfaces, like tables or forms, augment the user experience by enabling keyboard navigation:
De-focus using blur()
On a whim to remove the focus from a DOM element programmatically, use blur:
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:
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. 😉
Navigation: Easy peasy lemon squeezy
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.
Was this article helpful?