Skip to content
fa
Search Frontend Atlas
Search questions and concepts across the handbook.
UI Engineering & Machine Codingadvanced14 min read

How do you manage focus across modals, drawers, and dynamic UI?

Focus traps, restoration, initial focus, and the practical rules that keep keyboard and screen-reader users from getting lost.

Useful prerequisites

Keyboard users do not move through a page by looking at it; they move through the browser’s focus order. When a dialog opens, a menu expands or a route changes, the focus position needs to make sense in the new context. Focus management is the work of moving focus when necessary and restoring it when the interaction ends.

Keyboard users do not move through a page by looking at it; they move through the browser’s focus order. When a dialog opens, a menu expands or a route changes, the focus position needs to make sense in the new context. Focus management is the work of moving focus when necessary and restoring it when the interaction ends.

The quick version

Focus is part of the application’s state, not an afterthought. When you open a modal or drawer you must move focus into it, keep it there while the overlay is open (a focus trap), and restore focus to a sensible place when the overlay closes. Dynamic content that appears or disappears needs the same care — otherwise keyboard and screen-reader users lose their place or get stuck.

Why focus management is its own topic

Most of the time the browser’s default focus behaviour is fine. Links, buttons, and form controls do the right thing. The problems appear when we invent new surfaces: modals, drawers, popovers, command palettes, multi-step wizards, and any UI that mounts and unmounts large regions of the page.

In those cases the browser does not know what “should” be focused next. If we do nothing, focus can:

  • Stay on a control that is now hidden or covered.
  • Jump to the body or the first focusable element on the page.
  • Get stuck inside a closed dialog that is only visually hidden.
  • Move in an order that makes no sense relative to the visual layout.

These are not edge cases. They are the normal result of building interactive UI without an explicit focus plan.

Core rules that actually work

1. When a modal or drawer opens, move focus into it.
Usually to the first meaningful control or to a heading that has tabIndex={-1} so it can receive focus programmatically. Screen readers then announce the new context.

2. While it is open, trap focus inside it.
Tab and Shift+Tab should cycle through the focusable elements inside the overlay. Focus should not escape to the page behind. This is the focus trap.

3. When it closes, restore focus.
Send focus back to the element that opened the overlay, or to another logical place if that element no longer exists. Without restoration, keyboard users are dumped somewhere unpredictable.

4. Do not rely on display: none or visibility: hidden alone for “closed” state if the element can still receive focus.
If a dialog stays in the DOM, it needs inert (or an equivalent that removes it from the focus order) or it must be fully unmounted.

5. Initial focus and return focus are part of the component’s contract.
A reusable Modal should accept an option for where focus goes on open, and it should remember what to restore on close.

Concrete sketch of a focus trap

function trapFocus(container: HTMLElement) {
  const focusable = container.querySelectorAll<HTMLElement>(
    'a[href], button:not([disabled]), textarea, input, select, [tabindex]:not([tabindex="-1"])',
  );
  const first = focusable[0];
  const last = focusable[focusable.length - 1];

  function onKeyDown(event: KeyboardEvent) {
    if (event.key !== 'Tab') return;

    if (event.shiftKey) {
      if (document.activeElement === first) {
        event.preventDefault();
        last.focus();
      }
    } else {
      if (document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    }
  }

  container.addEventListener('keydown', onKeyDown);
  return () => container.removeEventListener('keydown', onKeyDown);
}

In production you also need to:

  • Handle the case where there are no focusable elements (focus the container itself).
  • Update the list of focusable elements if the content inside the modal changes.
  • Combine the trap with Escape-to-close and with proper aria-modal / role="dialog" (or the newer dialog element).

The native <dialog> element and the inert attribute remove a lot of this boilerplate when you can use them. Prefer the platform primitives when they fit.

Where it gets tricky

Focus restoration when the opener is gone.
If the button that opened the modal has been removed from the DOM (filtered list, page navigation, etc.), restore focus to a sensible fallback — often the main content landmark or the next logical item in a list.

Nested overlays.
A modal that opens another modal needs a stack. Closing the top one should restore focus to the element that opened it inside the lower modal, not all the way back to the original page control.

Dynamic lists and virtualised content.
If the currently focused item is scrolled out of the virtualised window and unmounted, focus disappears. Keep a stable focus reference or move focus to a nearby item before unmounting.

Programmatic focus vs user focus.
Calling element.focus() moves focus and, depending on the browser and options, may scroll the element into view. For large pages this can be jarring. focus({ preventScroll: true }) exists for a reason — use it when you are managing focus as part of a larger UI transition.

Focus visible vs focus.
:focus-visible lets you show a focus ring only for keyboard users. Do not remove focus outlines entirely. Keyboard users need a clear indicator of where they are.

Portals and React/Vue/Svelte root changes.
When a modal is rendered in a portal, it is no longer a DOM descendant of the trigger. Focus management has to be explicit; you cannot rely on simple ancestor relationships.

A common misunderstandings

  • “If it works with a mouse, focus is fine.”
    Mouse users never notice most focus bugs. Keyboard and screen-reader users hit them immediately.

  • “I can just set tabIndex={0} on everything.”
    That puts extra elements into the tab order and usually makes the experience worse. Prefer real interactive elements and use tabIndex={-1} only when you need to move focus programmatically.

  • “A focus trap is just listening for Tab.”
    A complete solution also handles initial focus, restoration, inert background content, Escape, and the case where the set of focusable elements changes while the trap is active.

What this changes in an application

Focus bugs are accessibility bugs and usability bugs at the same time. They show up in audits, in customer support tickets from power users, and in the experience of anyone who prefers or needs the keyboard. They are also among the most common regressions when teams add new overlays or rewrite navigation.

Treating focus as part of the component’s public behaviour (open → move focus in, close → restore focus) removes a whole class of issues. Doing it once in a solid Modal/Drawer primitive is far cheaper than fixing it in every feature.

Questions worth exploring next

  • How would you implement a focus trap that still allows a third-party widget inside the modal to manage its own focus?
  • What should happen to focus when a multi-step modal advances to the next step?
  • How do you test focus management without relying solely on visual inspection?
  • When would you choose the native <dialog> over a fully custom implementation?

References and next steps

Explore next