How to automatically set the focus to a textbox when a web page loads with HTML and JavaScript?

Spread the love

Sometimes, we want to automatically set the focus to a textbox when a web page loads HTML and JavaScript.

In this article, we’ll look at how to automatically set the focus to a textbox when a web page loads HTML and JavaScript.

How to automatically set the focus to a textbox when a web page loads with HTML and JavaScript?

To automatically set the focus to a textbox when a web page loads HTML and JavaScript, we use the autofocus attribute and the focus method.

For instance, we write

<input id="my-input" autofocus="autofocus" />

to focus on the input when the page loads with the autofocus attribute.

Then we write

if (!("autofocus" in document.createElement("input"))) {
  document.getElementById("my-input").focus();
}

to call focus on the input with JavaScript to move focus to it.

Conclusion

To automatically set the focus to a textbox when a web page loads HTML and JavaScript, we use the autofocus attribute and the focus method.

Leave a Reply

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