How to auto-highlight an input field on focus with JavaScript?

Sometimes, we want to auto-highlight an input field on focus with JavaScript.

In this article, we’ll look at how to auto-highlight an input field on focus with JavaScript.

How to auto-highlight an input field on focus with JavaScript?

To auto-highlight an input field on focus with JavaScript, we can call select on the element when the focus event is emitted.

For instance, we write:

<input type="text" value="test" />

to add an input with a value filled in.

Then we write:

const input = document.querySelector('input')

input.addEventListener('focus', () => {
  input.select()
})

to select the input with document.querySelector.

And then we call input.addEventListener to add a focus event listener.

In the event handler, we call input.select to highlight the value in the input box.

As a result, we see the input box value highlighted when we click inside the input box.

Conclusion

To auto-highlight an input field on focus with JavaScript, we can call select on the element when the focus event is emitted.