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.
Auto-Highlight an Input Field on Focus with JavaScript
To auto-highlight an input field on focus with JavaScript, we can listen to the focus event.
And in the event handler, we can call the select
method on the input to highlight it.
For instance, if we have the following input:
<input type='text' id='url-uinput' value='http://www.example.com/' />
We write:
const input = document.getElementById("url-uinput")
input.addEventListener('focus', () => {
input.select();
})
to select the input with the document.getElementById
method.
Then we call input.addEventListener
with 'focus'
to listen for the focus event.
We pass in an event handler function as the 2nd argument.
And in it, we call input.select
to select the text when we focus on the input box.
Now when we click on the input box, we see all the text in it highlighted.
Conclusion
To auto-highlight an input field on focus with JavaScript, we can listen to the focus event.
And in the event handler, we can call the select
method on the input to highlight it.