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
- 01Capture current focus
captureFocus records the active element without moving focus.
- 02Focus the dialog
Your app chooses the correct element inside the dialog.
- 03Restore 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.
| Status | Meaning | Application response |
|---|---|---|
| focused | Target became active | Continue the workflow |
| skipped | A documented eligibility check, browser failure, or restoration guard prevented focus | Preserve current focus and inspect reason |