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:
- Moves focus into the dialog when it opens.
- Keeps Tab and Shift+Tab inside the dialog.
- Closes when the user presses Escape.
- 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><divid="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-labelledbypoints 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 = nullfunction handleKeyDown(event) {if (event.key === "Escape") {closeModal()return}if (event.key !== "Tab") returnconst 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 backevent.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.activeElementmodal.hidden = falsegetFocusableElements(modal)[0].focus()document.addEventListener("keydown", handleKeyDown)}function closeModal() {modal.hidden = truedocument.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 hereexport function useFocusTrap(isOpen, onClose) {const ref = useRef(null)const onCloseRef = useRef(onClose)// Always use the latest onClose without re-running the trap effectuseEffect(() => {onCloseRef.current = onClose})useEffect(() => {if (!isOpen) returnconst container = ref.currentconst previouslyFocused = document.activeElementgetFocusableElements(container)[0]?.focus()function handleKeyDown(event) {if (event.key === "Escape") {onCloseRef.current()return}if (event.key !== "Tab") returnconst 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 nullreturn (<div className="backdrop"><divref={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? .