What focus trapping is for

Focus trapping keeps keyboard focus inside a given element by intercepting the two ways it could escape: Tab from the last focusable item sends focus back to the first, and Shift + Tab from the first sends it to the last. The pattern is a longstanding technique for accessible modal dialogs, which otherwise require marking everything outside the dialog inert. That workaround is no longer necessary for modals built with the dialog API, provided the implementation is done correctly.

The concept is easy to state and harder to implement, largely because of the number of pieces that need managing. An implementation has two jobs: collect all focusable elements inside the container, and manage focus from a keydown listener.

Collecting focusable elements

Only a handful of elements can receive focus:

  • a
  • button
  • input
  • textarea
  • select
  • details
  • iframe
  • embed
  • object
  • summary
  • dialog
  • audio[controls]
  • video[controls]
  • [contenteditable]
  • [tabindex]

getFocusableElements starts by querying the container for all of them:

export function getFocusableElements(container = document.body ) {

  return {
    get all () {
      const elements = Array.from(
        container.querySelectorAll(
          `a,
            button,
            input,
            textarea,
            select,
            details,
            iframe,
            embed,
            object,
            summary,
            dialog,
            audio[controls],
            video[controls],
            [contenteditable],
            [tabindex]
          `,
        ),
      )
    }
  }
}

Elements that are disabled, hidden, or set to display: none cannot be focused, so a filter pass removes them:

export function getFocusableElements(container = document.body ) {

  return {
    get all () {
      // ...
      return elements.filter(el => {
        if (el.hasAttribute('disabled')) return false
        if (el.hasAttribute('hidden')) return false
        if (window.getComputedStyle(el).display === 'none') return false
        return true
      })
    }
  }
}

Because the trap only concerns keyboard focus, the list is then narrowed to keyboard-focusable elements by dropping every tabindex value below 0:

export function getFocusableElements(container = document.body ) {
  return {
    get all () { /* ... */ },
    get keyboardOnly() {
      return this.all.filter(el => el.tabIndex > -1)
    }
  }
}

Trap logic needs the boundaries of that list, so getFocusableElements also exposes first and last getters, both reading from keyboardOnly:

export function getFocusableElements(container = document.body ) {
  return {
    // ...
    get first() { return this.keyboardOnly[0] },
    get last() { return this.keyboardOnly[0] },
  }
}

Handling the keydown event

The trap is wired up with addEventListener:

const container = document.querySelector('.some-element')
container.addEventListener('keydown', event => {/* ... */})

Only two gestures matter: Tab alone and Tab with Shift. Both are detectable from scratch with event.key for the Tab key and event.shiftKey for the modifier:

export function isTab(event) {
  return !event.shiftKey && event.key === 'Tab'
}

export function isShiftTab(event) {
  return event.shiftKey && event.key === 'Tab'
}

Pressing event.key and event.shiftKey together yields the isTab and isShiftTab helpers. Since no other key is handled, an early return skips everything else:

container.addEventListener('keydown', event => {
  if (event.key !== 'Tab') return

  if (isTab(event)) // Handle Tab
  if (isShiftTab(event)) // Handle Shift Tab
  /* ... */
})

Deciding when to redirect focus

The remaining piece is knowing where focus currently sits. document.activeElement provides that, and comparing it against the first and last items determines whether the trap intercepts the event or lets the browser's default focus behavior run:

container.addEventListener('keydown', event => {
  // ...
  const focusables = getFocusableElements(container)
  const first = focusables.first
  const last = focusables.last

  if (document.activeElement === last && isTab(event)) {
    // Shift focus to the first item
  }

  if (document.activeElement === first && isShiftTab(event)) {
    // Shift focus to the last item
  }
})

If interception is needed, focus moves focus to the target item:

container.addEventListener('keydown', event => {
  // ...

  if (document.activeElement === last && isTab(event)) {
    first.focus()
  }

  if (document.activeElement === first && isShiftTab(event)) {
    last.focus()
  }
})