Focus Trap

Accessibilityintermediate

// Definition

Deliberately confining keyboard focus within a region — correct inside an open modal (Tab should cycle within it, not escape to the page behind), but a serious bug anywhere else (a user who can't Tab out is stuck). The accessible pattern: trap focus while a modal is open, restore it to the trigger on close.

// Why it matters

Focus trapping is a two-sided QA concern: its absence in modals lets keyboard users tab into the obscured page behind (confusing, broken), while an unintended trap anywhere strands the user entirely. Both are WCAG failures. Testing it needs nothing but the Tab key, so there's no excuse to skip it.

// How to test

// Modal: focus must stay inside while open, return to trigger on close
cy.get('[data-cy=open-modal]').click()
cy.focused().should('be.visible')              // focus moved into modal
// tab through every focusable, confirm it cycles and never leaves the modal
cy.get('body').type('{esc}')
cy.focused().should('have.attr', 'data-cy', 'open-modal')  // restored to trigger
// Anti-test: NO region outside a modal should trap focus

// Common mistakes

  • Modals that don't trap focus (Tab escapes to the page behind)
  • Traps that never release, stranding keyboard users
  • Not restoring focus to the trigger element when the modal closes

// Related terms