How to detect if input is focused with JavaScript?

Sometimes, we want to detect if input is focused with JavaScript

In this article, we’ll look at how to detect if input is focused with JavaScript

How to detect if input is focused with JavaScript?

To detect if input is focused with JavaScript, we can check is document.activeElement is the input.

For instance, we write

e.target === document.activeElement

in an event handler to check if the element that triggered the event, which is e.target is the same as document.activeElement.

document.activeElement is the element that has focus on the page.

Conclusion

To detect if input is focused with JavaScript, we can check is document.activeElement is the input.