In web development, it’s often necessary to determine which element on a webpage currently has focus. This can be useful for implementing custom navigation, accessibility features, or dynamic user interfaces. In this tutorial, we’ll explore how to find the currently focused DOM element using JavaScript.
Introduction to Document Active Element
The document.activeElement
property returns the currently focused element in a document. This property is supported by all major browsers and is part of the HTML5 specification. To access the active element, you can simply use document.activeElement
.
const focusedElement = document.activeElement;
Note that if no element has focus or the browser window doesn’t have focus, document.activeElement
will return the body
element.
Checking for Focus
To verify whether an element actually has focus, you can use the document.hasFocus()
method. This method returns a boolean indicating whether the document has focus.
const hasFocus = document.hasFocus();
You can combine these two properties to ensure that the focused element is not the body
or html
element and that the document has focus.
let focusedElement = null;
if (
document.hasFocus() &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement
) {
focusedElement = document.activeElement;
}
Alternative Approach Using jQuery
If you’re using jQuery, you can use the :focus
pseudo-class to select the currently focused element.
const $focusedElement = $(":focus");
Note that this approach requires jQuery version 1.6 or later.
Handling Edge Cases
Some browsers may return null
or the body
element when no element has focus. To handle these cases, you can add additional checks.
let focusedElement = document.activeElement;
if (!focusedElement || focusedElement === document.body) {
focusedElement = null;
}
Example Use Cases
- Custom Navigation: You can use the
document.activeElement
property to implement custom navigation using arrow keys or other keyboard shortcuts. - Accessibility Features: By checking which element has focus, you can provide accessibility features such as screen reader support or high contrast mode.
- Dynamic User Interfaces: You can use the focused element to dynamically update your user interface, such as highlighting the currently selected item.
Best Practices
- Always check for
document.hasFocus()
before accessing the active element to ensure that the document has focus. - Use
document.activeElement
instead of:focus
pseudo-class for better performance. - Handle edge cases where the browser may return
null
or thebody
element when no element has focus.
By following these guidelines and using the document.activeElement
property, you can easily determine which DOM element currently has focus in your web application.