Glossary / Focus management
Focus management
Focus management is the deliberate placement and movement of keyboard focus as an interface changes. Good focus management keeps users oriented when dialogs open, routes change, errors appear, or content is inserted; poor management causes focus to disappear, jump unexpectedly, or remain behind an overlay. The browser normally manages focus well for native controls, so application code should intervene only when a meaningful state transition requires it.
What to know
- DOM focus is commonly exposed through
document.activeElement; it is distinct from a screen reader’s virtual cursor or browse-mode position. - On opening a modal dialog, move focus into it—often to the first meaningful control or a static heading with
tabindex="-1"for long content. Keep interaction within the modal while it is modal. - On closing, restore focus to the invoking control when it still exists; if not, choose a logical next destination.
- For single-page navigation, announce or focus the new page heading/main region according to the application’s navigation model; do not reset focus on every small render.
- Use
focus()after the target is mounted. In React-like render cycles, coordinate with refs and lifecycle/effect timing; avoid focusing stale or hidden nodes. - WCAG 2.2 includes Focus Visible, Focus Not Obscured (Minimum), and Focus Appearance criteria. A focused item should be visible and not covered by author-created content.
autofocuscan unexpectedly move users and is not a substitute for a clear interaction sequence.
Engineering patterns
Use native <dialog> or a vetted dialog component when possible, but still verify focus entry, modal behavior, Escape policy, accessible name, and return focus in supported browsers. For async validation, focus the error summary or first invalid field, and link summary messages to their fields. For route changes, update document.title, make the new context perceivable, and preserve expected browser history behavior. Be cautious with focus traps: they belong only in genuinely modal experiences and must have a keyboard escape/close path.
Interview questions
- When should code move focus? When the user initiates a transition that changes context and the browser’s natural focus would otherwise leave them disoriented.
- Where should focus go after closing a dialog? Usually back to the opener; if the opener no longer exists, to a logical successor.
- Why is
aria-livenot a replacement for focus? Live regions announce updates but do not necessarily move the user to a new interaction context; each solves a different problem. - How do you prevent focus from being hidden? Account for sticky UI and overlays, scroll the focused control into view when appropriate, and test at zoom and viewport breakpoints.
- What is a common SPA accessibility bug? Visual route content changes while title and focus remain on the old context, leaving keyboard and screen-reader users unaware of navigation.