DEV Community

Cover image for How to focus on input HTML tag using JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to focus on input HTML tag using JavaScript?

Originally posted here!

Focusing on the input tag is a common feature in modern websites to give attention to the user visiting.

To set focus on an input tag element in HTML, you can use the focus() method on the element using JavaScript.

Let's say we have an input tag in HTML like this,

<!-- Input tag -->
<input id="myInput" type="text" placeholder="Enter some text here" />
Enter fullscreen mode Exit fullscreen mode

And we want the input tag to be on focus whenever the user visits the website.

Let's focus the input tag element using focus() method like this,

// first get a reference to the input tag
const input = document.querySelector("#myInput");

// use the focus method
input.focus();
Enter fullscreen mode Exit fullscreen mode

Now the input tag is focussed. ⭐️

See this example live in JSBin.

Feel free to share if you found this useful 😃.


Top comments (0)