How to check if an element is focused in JavaScript

One of the typical task that occurs when working with JavaScript is checking if an element on a web page has the focus.

The focus refers to the element that is currently selected or active, such as an input field or a button.

In this article, we will show you the different methods to check if an element is focused in JavaScript, and provide a step-by-step instructions with code examples.

What is the Importance of Checking Element Focus?

Before moving into the different methods of checking element focus, let’s understand first why this task holds importance in web development.

The ability to identify whether an element has the focus allows us to increase user experience and create collective features.

Now, let’s move into the methods for checking element focus in JavaScript.

Methods to check if an element is focused in JavaScript

Here are the following methods to check if an element is focused in JavaScript:

Method 1: Using the document.activeElement Property

The document.activeElement property returns the currently focused element on the page.

We can use this property to check if a specific element is focused.

Here’s an example code that uses the document.activeElement:

const element = document.getElementById('btnInput');

if (element === document.activeElement) {
    console.log('The element is focused in JavaScript.');
} else {
    console.log('The element is not focused in JavaScript.');
}

In this example code, we access a reference to the proper element using its “ID” and then compare it with the active element.

If they match, we log a message that demonstrating the element is focused; otherwise, we log a message declaring that the element is not focused.

Method 2: Using the document.hasFocus()

Another method to identify if an element is focused involves by applying the document.hasFocus() method.

This method returns a Boolean value showing the document has focus.

Here’s an example code that use document.hasFocus():

const isFocused = document.hasFocus();

if (isFocused) {
    console.log('The document has focus element.');
} else {
    console.log('The document does not have focus element.');
}

By using document.hasFocus(), we can figure out that if the document has focus, the element we are interested in is also focused.

Method 3: Using Event Listeners

We can apply the event listeners to detect when an element proceeds or loses focus.

By connecting the proper event handlers, we can execute the different actions based on the element’s focus state.

Here’s an example code that uses Event Listeners:

const element = document.getElementById('btnEvent');

element.addEventListener('focus', () => {
    console.log('The element gained focus the element.');
});

element.addEventListener('blur', () => {
    console.log('The element lost focus in the element.');
});

In this example code, we listen for the focus event, which is triggered when the element gains focus.

Similarly, we listen for the blur event, which is removed when the element loses focus.

Inside the event handlers, we can perform any applicable operations.

Method 4: Using the :focus CSS Pseudo-Class

The :focus CSS pseudo-class enables us to style elements based on their focus state.

We can apply this pseudo-class in combination with JavaScript to identify if an element is focused.

Here’s an example code that uses the :focus CSS Pseudo-Class:

const elementSample = document.getElementById('btnClass');

const isFocused = getComputedStyle(elementSample, ':focus') !== null;

if (isFocused) {
    console.log('The element is focused.');
} else {
    console.log('The element is not focused.');
}

By using the getComputedStyle function, we can check if the element has the :focus pseudo-class applied to it.

Method 5: Using the tabindex Attribute

The tabindex attribute allows us to control the order in which elements receive focus when navigating with the Tab key.

We can utilize this attribute to check if an element is focused programmatically.

Here’s an example code:

const elementSample = document.getElementById('btnEvent');

const isFocused = elementSample === document.activeElement;

if (isFocused) {
    console.log('The element is focused.');
} else {
    console.log('The element is not focused.');
}

In this code example, we compare the proper element with the active element to determine if it is focused.

FAQs

How can I check if an input element is focused?

To check if an input element is focused in JavaScript, you can use any of the methods mentioned in this article.

Can I determine if an element inside an iframe is focused?

Yes, it is possible to determine if an element inside an iframe is focused. You can access the iframe’s content using the contentDocument property and then use any of the methods discussed earlier to check if the desired element has focus.

Is it possible to check if a button element is focused?

Absolutely! The same methods we have covered in this article can be applied to check if a button element is focused.

Whether it is using the document.activeElement property, event listeners, or CSS pseudo-classes, you can easily determine if a button element has the focus.

Are there any browser compatibility issues when checking element focus?

Most of the modern browsers fully support the methods discussed in this article.

However, it is always a good practice to test your code across different browsers and versions to ensure compatibility.

Be aware that older browsers may have limited support for several methods or may require alternative methods.

Conclusion

In this article, we have discussed the different methods to check if an element is focused in JavaScript.

Also, we have learned about using properties like document.activeElement and document.hasFocus(), as well as event listeners, CSS pseudo-classes, and the tabindex attribute.

Additional Resources

Leave a Comment