Sometimes, we want to automatically set the focus to a textbox when a web page loads with JavaScript.
In this article, we’ll look at how to automatically set the focus to a textbox when a web page loads with JavaScript.
How to automatically set the focus to a textbox when a web page loads with JavaScript?
To automatically set the focus to a textbox when a web page loads with JavaScript, we can call the focus
method on the text box in the window.onload
handler.
For instance, we write
window.onload = () => {
document.getElementById("Box1").focus();
};
to set window.onload
to a function that runs when all the elements on the page are loaded.
In it, we get the text box with
document.getElementById("Box1")
And then we call focus
on it.
Conclusion
To automatically set the focus to a textbox when a web page loads with JavaScript, we can call the focus
method on the text box in the window.onload
handler.