<input id="myTextField" value="Text field." />
<button id="focusButton">Click to set focus on the text field</button>HTMLElement: focus() method / notebook
HTMLElement: focus() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
document.getElementById("focusButton").addEventListener("click", () => {
document.getElementById("myTextField").focus();
});<button id="myButton">Button</button>
<button id="focusButton">Click to set focus on "Button"</button>
<button id="focusButtonVisibleIndication">
Click to set focus and focusVisible on "Button"
</button>document.getElementById("focusButton").addEventListener("click", () => {
document.getElementById("myButton").focus();
});
document
.getElementById("focusButtonVisibleIndication")
.addEventListener("click", () => {
document.getElementById("myButton").focus({ focusVisible: true });
});<button id="focus_scroll">Click to set focus on off-screen button</button>
<button id="focus_no_scroll">
Click to set focus on offscreen button without scrolling
</button>
<div id="container">
<button id="myButton">Button</button>
</div>