Skip to main content

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

๐Ÿ“– MDN: HTMLElement.focus()

Browser supportโ€‹

APIChromeEdgeFirefoxSafariiOS SafariBaseline
HTMLElement.focusโœ… 1+โœ… 12+โœ… 1.5+โœ… 3+โœ… 1+ [1]Widely available
Document.activeElementโœ… 2+โœ… 12+โœ… 3+โœ… 7+โœ… 7+Widely available
  1. 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 in container
  • focusLast(container) โ€” focuses the last focusable element in container
  • focusNext(container) โ€” focuses the element after the currently focused one
  • focusPrev(container) โ€” focuses the element before the currently focused one
  • focusBySelector(container, selector) โ€” focuses the element matching selector

See the API reference for full signatures.