DOM

Focus helpers

Helpers for capturing, moving, and restoring focus in dialogs and other app interactions.

Capture and restore application focus

Call these helpers from dialogs and other interactions that your app controls. Do not move focus for streaming text or routine status updates.

typescript
const capture = captureFocus(document);
const opened = focusElement(dialogHeading, { preventScroll: true });

// After the application-owned interaction closes:
const restored = restoreFocus(capture, {
  onlyIfFocusWithin: dialog,
});

How this code works

  1. 01
    Capture current focus

    captureFocus records the active element without moving focus.

  2. 02
    Focus the dialog

    Your app chooses the correct element inside the dialog.

  3. 03
    Restore when appropriate

    onlyIfFocusWithin leaves focus alone if the user moved outside the dialog.

Options and return values

captureFocus(document)FocusCaptureFunction

Captures the deep active element from the supplied document.

Default
global document
focusElement(element, options)FocusResultFunction

Attempts focus and reports focused or a stable skipped reason.

Default
preventScroll: true
restoreFocus(capture, options)FocusResultFunction

Restores only when the captured target remains eligible and optional guards still match.

Default
n/a

FocusResult

Results are explicit so applications can test focus workflows without guessing.

StatusMeaningApplication response
focusedTarget became activeContinue the workflow
skippedA documented eligibility check, browser failure, or restoration guard prevented focusPreserve current focus and inspect reason