Sometimes, we want to check if an input field has focus with JavaScript.
In this article, we’ll look at how to check if an input field has focus with JavaScript.
How to check if an input field has focus with JavaScript?
To check if an input field has focus with JavaScript, we can use the document.activeElement
property to get the element in focus.
For instance, we write:
<input>
to add an input.
Then we write:
console.log(document.querySelector('input') === document.activeElement)
to check if the input element is focused.
document.activeElement
‘s value is the element that’s current in focus.
Conclusion
To check if an input field has focus with JavaScript, we can use the document.activeElement
property to get the element in focus.