JavaScript Reference ยท DOM: Document and Elements
HTMLElement.focus()
Reference for HTMLElement.focus() and blur(): move keyboard focus from code, the preventScroll and focusVisible options, tabindex rules and accessibility notes.
The focus() method gives an element keyboard focus, so typing goes to it and screen readers announce it. The counterpart, blur(), removes focus again. Both fire the usual focus events, and document.activeElement always tells you which element currently has focus.
Only focusable elements can take focus: links with href, buttons, form controls, elements with tabindex, and a few others. Calling focus() on anything else does nothing.
input.focus(); input.focus({ preventScroll: true });
Try it
Syntax
element.focus() element.focus(options) element.blur()
Parameters
| Name | Description |
|---|---|
options.preventScroll |
If true, the browser does not scroll the element into view when focusing it. Default false. |
options.focusVisible |
Newer option. true asks for the focus ring to show, false to hide it; omitted lets the browser decide. |
Return value
undefined for both focus() and blur().
Usage notes
tabindexcontrols focusability.tabindex="0"puts a custom element in the normal Tab order;tabindex="-1"lets scripts focus it but keeps it out of the Tab order. Positive values override the natural order and should be avoided.- Focus is not scroll. By default
focus()scrolls the element into view. UsepreventScroll: truewhen you scroll yourself, for example withscrollIntoView(). - Hidden or disabled elements ignore it. Elements that are
display: none,visibility: hidden, disabled, or inside an inert subtree cannot take focus. A common bug is callingfocus()right after unhiding an element in a way that has not yet rendered; focus after the element is visible. - Manage focus on route changes and dialogs. After a single-page navigation, move focus to the new heading (with
tabindex="-1"). When a modal closes, return focus to the button that opened it. - Never trap or steal focus without a reason. Autofocusing a field on page load can disrupt screen reader users; the
autofocusattribute is better for the one field a page is about. - Focus events.
focusandblurdo not bubble;focusinandfocusoutdo, which makes them the right choice for delegated listeners. document.activeElementisdocument.body(ornull) when nothing is focused. The value inside a shadow tree is the shadow host unless you ask the shadow root.- Selecting text. For text inputs,
input.select()highlights the content after focusing it.
Browser support
focus() and blur() work in every browser. The preventScroll option is supported in all current browsers; focusVisible is recent, so check a compatibility table before relying on it.