Categories
JavaScript Answers

How to check if an input field has focus with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *