focus
Focus management helpers for moving focus to the first, last, next, or previous focusable element within a container, or to a specific element by selector.
Import: @rtorcato/browser-common/focus
Browser supportโ
| API | Chrome | Edge | Firefox | Safari | iOS Safari | Baseline |
|---|---|---|---|---|---|---|
HTMLElement.focus | โ 1+ | โ 12+ | โ 1.5+ | โ 3+ | โ 1+ [1] | Widely available |
Document.activeElement | โ 2+ | โ 12+ | โ 3+ | โ 7+ | โ 7+ | Widely available |
- iOS Safari: If there's no hardware keyboard connected and the user has not yet interacted with the page, then calling focus() on an <input> element has no effect (for example, the element does not match the :focus selector).
โ
supported ยท โ partial ยท โ not supported ยท [n] see note. Generated from MDN browser-compat-data and web-features. caniuse: HTMLElement.focus ยท Document.activeElement
Exampleโ
import { focusFirst, focusNext, focusBySelector } from '@rtorcato/browser-common/focus'
// open a dialog and focus its first focusable element
focusFirst(dialog)
// advance focus within a form on Tab-like custom navigation
focusNext(form)
// jump straight to a known field
focusBySelector(form, 'input[name="email"]')
Exportsโ
focusFirst(container)โ focuses the first focusable element incontainerfocusLast(container)โ focuses the last focusable element incontainerfocusNext(container)โ focuses the element after the currently focused onefocusPrev(container)โ focuses the element before the currently focused onefocusBySelector(container, selector)โ focuses the element matchingselector
See the API reference for full signatures.