captureFocus()
Return focus to the dialog opener.
Try the example
Open the project settings dialog and close it with its button or Escape. Notice the focus ring returning to the control that opened it.
Open the dialog using the keyboard to follow the focus ring.
Ready. Focus will return to the opener.
Add it to your project
- Copy the HTML. Place the markup inside the component where this behavior belongs. The preview’s visual classes are website styles; use your own design system.
- Connect the behavior. Copy the JavaScript tab and call its exported
mount(element)after your component’s elements exist. Replace simulated delays and data operations with your own application code. - Clean up. Call the returned cleanup when the component unmounts. It aborts the example’s listeners and releases the helper’s timers, observers or state.
API and lifecycle
Call captureFocus() immediately before opening a dialog. It remembers the currently focused element and returns a restore function; it does not move focus into the dialog or trap it.
- Interface
returns restore callback- Lifecycle
- Call the returned function after the dialog closes. It restores focus only when the original element is still connected to the document.
Accessibility and safety
Implementation notes
Initialize after the DOM is available. Keep native controls and keyboard interactions intact; release listeners and timers on unmount.
Use a native dialog or an accessible modal for focus containment. Avoid adding a second focus trap to a component that already manages focus.
What to check
Open using the keyboard, close with the dialog's control, and confirm focus returns to the opener. Also test closing after the opener has been removed.