DOM Methods
HTMLElement.focus()
Sets keyboard focus if the element can receive it. Use to place focus after a meaningful user action or validation error. The preventScroll option can prevent automatic scrolling. Do not unexpectedly steal focus during normal reading. Example result: true.
Formal Syntax & Structure
html syntaxhtml
element.focus(options)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| options | FocusOptions | Optional focus options such as preventScroll. |
Return Value
undefined
No return value.
Working Example
Example Snippethtml
<button id="demo">Save</button><p> Result: <output id="result"></output></p><script> const e = document.getElementById('demo'); const result = value => { document.getElementById("result").textContent = String(value); }; e.focus({preventScroll:true}); result(document.activeElement===e);</script>