Focus Trapping for Better Web Accessibility

Improve accessibility with "focus trapping" for modals and popovers.

When dealing with elements that provide an "out of flow" reading order, focus trapping can be useful for users with assistive technology.

What is the issue with modals and popovers?

Modals and popovers are dialogs that introduce a new "layer", or overlay, of content that is meant to be consumed when initiated. Sighted users can see what is meant to be focused on, read it or take action, and close the dialog to be on their way. The issue becomes apparent when using assistive technology such as a screen reader, or when navigating with only a keyboard. Those users aren't told that a dialog opened, and pressing Tab keeps moving focus through the links and buttons on the page behind it.

What is focus trapping and what does it solve?

Focus trapping keeps keyboard focus inside the dialog while it's open. Tabbing past the last element wraps back to the first one, and Shift+Tab on the first element wraps to the last. The user can't wander off into content they can't see, and they leave the dialog by closing it.

A focus trap keeps keyboard focus inside a dialog until the dialog is closed.

A good modal does four things:

  1. Moves focus into the dialog when it opens.
  2. Keeps Tab and Shift+Tab inside the dialog.
  3. Closes when the user presses Escape.
  4. Moves focus back to the element that opened it when it closes.

The dialog markup

First the HTML. The ARIA attributes tell screen readers what this element is:

<button id="open-modal">Subscribe</button>
<div
id="modal"
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
hidden
>
<h2 id="modal-title">Subscribe to the newsletter</h2>
<label for="email">Email</label>
<input id="email" type="email" />
<button>Subscribe</button>
<button id="close-modal">Close</button>
</div>
  • role="dialog" announces the element as a dialog.
  • aria-modal="true" tells assistive technology that content outside the dialog is inert while it's open.
  • aria-labelledby points at the heading so the dialog gets announced with its title, e.g. "Subscribe to the newsletter, dialog".

Finding the focusable elements

To trap focus we need to know the first and last elements that can receive focus inside the dialog. This selector covers the common ones:

const FOCUSABLE_SELECTOR = [
"a[href]",
"area[href]",
"button:not([disabled])",
"input:not([disabled]):not([type='hidden'])",
"select:not([disabled])",
"textarea:not([disabled])",
"iframe",
"[tabindex]:not([tabindex='-1'])",
"[contenteditable='true']",
].join(",")
const getFocusableElements = (container) =>
Array.from(container.querySelectorAll(FOCUSABLE_SELECTOR))

querySelectorAll returns them in DOM order, which is also the tab order as long as you avoid positive tabindex values. If you want a refresher on selectors, see How to use document.querySelector().

A focus trap in vanilla JavaScript

Now we can put it together:

const modal = document.getElementById("modal")
const openButton = document.getElementById("open-modal")
const closeButton = document.getElementById("close-modal")
let previouslyFocused = null
function handleKeyDown(event) {
if (event.key === "Escape") {
closeModal()
return
}
if (event.key !== "Tab") return
const focusable = getFocusableElements(modal)
const first = focusable[0]
const last = focusable[focusable.length - 1]
if (!modal.contains(document.activeElement)) {
// Focus somehow left the dialog, bring it back
event.preventDefault()
first.focus()
} else if (event.shiftKey && document.activeElement === first) {
event.preventDefault()
last.focus()
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault()
first.focus()
}
}
function openModal() {
previouslyFocused = document.activeElement
modal.hidden = false
getFocusableElements(modal)[0].focus()
document.addEventListener("keydown", handleKeyDown)
}
function closeModal() {
modal.hidden = true
document.removeEventListener("keydown", handleKeyDown)
previouslyFocused.focus()
}
openButton.addEventListener("click", openModal)
closeButton.addEventListener("click", closeModal)

When the modal opens we save document.activeElement (the button that opened it), show the dialog and focus its first focusable element. The keydown listener does the trapping. We only step in when focus is on the first or last element, and everywhere else the browser tabs normally. On close we remove the listener and send focus back to previouslyFocused so keyboard users pick up right where they left off.

Note: Screen readers don't all respect aria-modal yet. For better support, also set aria-hidden="true" on your main page content while the dialog is open (and make sure the dialog isn't inside that content).

A focus trap hook in React

In React the same logic fits nicely into a hook:

import { useEffect, useRef } from "react"
// FOCUSABLE_SELECTOR and getFocusableElements from above go here
export function useFocusTrap(isOpen, onClose) {
const ref = useRef(null)
const onCloseRef = useRef(onClose)
// Always use the latest onClose without re-running the trap effect
useEffect(() => {
onCloseRef.current = onClose
})
useEffect(() => {
if (!isOpen) return
const container = ref.current
const previouslyFocused = document.activeElement
getFocusableElements(container)[0]?.focus()
function handleKeyDown(event) {
if (event.key === "Escape") {
onCloseRef.current()
return
}
if (event.key !== "Tab") return
const focusable = getFocusableElements(container)
const first = focusable[0]
const last = focusable[focusable.length - 1]
if (!container.contains(document.activeElement)) {
event.preventDefault()
first.focus()
} else if (event.shiftKey && document.activeElement === first) {
event.preventDefault()
last.focus()
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault()
first.focus()
}
}
document.addEventListener("keydown", handleKeyDown)
return () => {
document.removeEventListener("keydown", handleKeyDown)
previouslyFocused?.focus()
}
}, [isOpen])
return ref
}

The hook returns a ref to put on the dialog. The effect runs when isOpen becomes true, and its cleanup function runs when the dialog closes or unmounts, which is the perfect place to restore focus. Keeping onClose in a ref means passing an inline arrow function won't restart the trap on every render.

Using it in a modal component:

const Modal = ({ isOpen, onClose, title, children }) => {
const ref = useFocusTrap(isOpen, onClose)
if (!isOpen) return null
return (
<div className="backdrop">
<div
ref={ref}
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
>
<h2 id="modal-title">{title}</h2>
{children}
<button onClick={onClose}>Close</button>
</div>
</div>
)
}

Here it is working. Open the dialog and try Tab, Shift+Tab and Escape:

Get new front-end tips in your inbox.

If you'd rather not maintain this yourself, most component libraries come with accessible dialogs that trap focus for you. The Chakra UI Modal and Radix UI Dialog handle all of this out of the box, and if you want to build your own, React Aria has a FocusScope component that traps focus with a single contain prop.

Have some feedback on this post? .