Pattern Accessibility Beginner
Focus Trap
A focus trap cycles Tab and Shift+Tab through the interactive elements inside a modal or dialog, so focus stays in the modal until it closes.
The problem
Once a modal opens, mouse users can see the dimmed overlay and know that they need to finish with the modal first. A keyboard user who presses Tab might end up on a button underneath the overlay, because the page behind the modal is still in the tab order, even though the modal covers it on screen.
The pattern
A focus trap listens for Tab and Shift+Tab keypresses inside the modal. It finds all the focusable elements inside your modal, such as buttons, links, form inputs, and elements with tabindex="0". If focus is on the last one and the user presses Tab, the trap moves focus back to the first, and if focus is on the first one and the user presses Shift+Tab, it moves focus to the last.
Problem
I’ve watched users Tab around a modal, past the close button, into the page footer, through the entire navigation menu, and all the way back around before finally landing on the modal content, because the Tab key moved through the page as if the modal wasn’t there.
It’s worse for screen reader users, because their screen reader can still read out the page behind the overlay, and if they can’t see the overlay, they have no way of knowing they’re meant to stay in the modal.
Solution
aria-modal="true" tells screen readers the background is inert, and adding the inert attribute to the main content behind the modal means keyboard users can’t focus that content and screen readers skip it. If I were building a new modal, I’d start with a native <dialog>, because when you open it with showModal(), the browser makes the rest of the page inert, and you don’t need a custom trap.
Your modal also needs an obvious way out, so the Escape key should close it, and there should be a visible close button.
A trap only keeps focus in the modal. Focus Management covers moving focus into the modal when it opens, and back to the element that opened it when it closes. Keyboard Navigation covers the keys that operate the widgets inside the modal.
Example
Native Dialog
I’d start with a <dialog> opened with showModal(). The browser makes the rest of the page inert, moves focus into the dialog, closes it on Escape, and in current browsers returns focus to the button that opened it, so the script only has to open and close it.
<button id="open">Edit profile</button>
<dialog id="profile-dialog" aria-labelledby="profile-title">
<h2 id="profile-title">Edit profile</h2>
<label>Name <input name="name" /></label>
<button id="close">Close</button>
</dialog>
<script>
const dialog = document.getElementById('profile-dialog');
document.getElementById('open').addEventListener('click', () => dialog.showModal());
document.getElementById('close').addEventListener('click', () => dialog.close());
</script>
Hand-Written Focus Trap
The trap below is for a custom modal where you can’t use <dialog>. In the keydown handler, pressing Shift+Tab on the first focusable element moves focus to the last one, and pressing Tab on the last one moves focus to the first. Each version looks up the focusable elements inside the handler, on each keypress, so the list is still right after the modal’s content changes. Each one also moves focus to the first focusable element when the modal opens. They don’t return focus to the element that opened the modal when it closes, and the modal example in Focus Management shows that part.
const FOCUSABLE =
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
function Modal({ children, onClose }) {
const modalRef = useRef();
useEffect(() => {
const modal = modalRef.current;
if (!modal) return;
const trapFocus = (e) => {
if (e.key === 'Escape') { onClose(); return; }
if (e.key !== 'Tab') return;
const focusable = modal.querySelectorAll(FOCUSABLE);
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey && document.activeElement === first) {
last.focus();
e.preventDefault();
} else if (!e.shiftKey && document.activeElement === last) {
first.focus();
e.preventDefault();
}
};
modal.addEventListener('keydown', trapFocus);
return () => modal.removeEventListener('keydown', trapFocus);
}, [onClose]);
// Moves focus into the modal once, when it mounts
useEffect(() => {
modalRef.current?.querySelector(FOCUSABLE)?.focus();
}, []);
return (
<div ref={modalRef} role="dialog" aria-modal="true">
{children}
</div>
);
} <template>
<div v-if="isOpen" ref="modalRef" role="dialog" aria-modal="true" @keydown="handleKeydown">
<h2>Modal Title</h2>
<slot />
<button @click="$emit('close')">Close</button>
</div>
</template>
<script setup>
import { ref, watch } from 'vue';
const FOCUSABLE =
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
const props = defineProps(['isOpen']);
const emit = defineEmits(['close']);
const modalRef = ref(null);
const handleKeydown = (e) => {
if (e.key === 'Escape') { emit('close'); return; }
if (e.key !== 'Tab') return;
const focusable = modalRef.value.querySelectorAll(FOCUSABLE);
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey && document.activeElement === first) {
last.focus();
e.preventDefault();
} else if (!e.shiftKey && document.activeElement === last) {
first.focus();
e.preventDefault();
}
};
// flush: 'post' runs the callback after v-if has rendered the dialog
watch(
() => props.isOpen,
(isOpen) => { if (isOpen) modalRef.value?.querySelector(FOCUSABLE)?.focus(); },
{ flush: 'post' }
);
</script> const FOCUSABLE =
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
class FocusTrapDialog extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.render();
this.setupFocusTrap();
}
// Slotted content stays in the light DOM, as children of the host, so
// shadowRoot.querySelectorAll() can't find it. The slot comes before the
// Close button in the template, so the slotted elements go first in the list.
getFocusable() {
return [
...this.querySelectorAll(FOCUSABLE),
...this.shadowRoot.querySelectorAll(FOCUSABLE),
];
}
setupFocusTrap() {
this.addEventListener('keydown', (e) => {
if (e.key === 'Escape') { this.close(); return; }
if (e.key !== 'Tab') return;
const focusable = this.getFocusable();
const first = focusable[0];
const last = focusable[focusable.length - 1];
// For an element in the shadow root, document.activeElement only reports
// the host, so check the shadow root first. Slotted elements are reported
// by document.activeElement as usual.
const active = this.shadowRoot.activeElement ?? document.activeElement;
if (e.shiftKey && active === first) {
last.focus();
e.preventDefault();
} else if (!e.shiftKey && active === last) {
first.focus();
e.preventDefault();
}
});
this.getFocusable()[0]?.focus();
}
close() { this.dispatchEvent(new CustomEvent('close')); }
render() {
this.shadowRoot.innerHTML = `
<div role="dialog" aria-modal="true">
<h2>Dialog Title</h2>
<slot></slot>
<button id="close-btn">Close</button>
</div>
`;
this.shadowRoot.getElementById('close-btn').addEventListener('click', () => this.close());
}
}
customElements.define('focus-trap-dialog', FocusTrapDialog); Background Inert
The inert attribute disables the background content completely, so it can’t receive focus and screen readers skip it. With the background inert, the modal’s controls are the only focusable elements left on the page, so focus stays inside the modal without a trap, the same way it does in a native <dialog>. The modal is rendered through a portal outside #root, so it isn’t made inert along with the background.
import { createPortal } from 'react-dom';
function Modal({ isOpen, onClose, children }) {
const dialogRef = useRef();
const previousFocusRef = useRef();
useEffect(() => {
const mainContent = document.querySelector('#root');
if (isOpen) {
previousFocusRef.current = document.activeElement;
mainContent?.setAttribute('inert', '');
dialogRef.current?.focus();
} else {
mainContent?.removeAttribute('inert');
previousFocusRef.current?.focus();
}
return () => mainContent?.removeAttribute('inert');
}, [isOpen]);
if (!isOpen) return null;
return createPortal(
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
tabIndex={-1}
onKeyDown={(e) => e.key === 'Escape' && onClose()}
>
<h2>Modal Title</h2>
{children}
<button onClick={onClose}>Close</button>
</div>,
document.body
);
}
Using focus-trap Library
If you do need a script-based trap, the focus-trap-react library handles edge cases, such as hidden or disabled elements and nested traps, that the hand-written version above doesn’t. Its returnFocusOnDeactivate option also sends focus back to the element that opened the modal when it closes.
import { FocusTrap } from 'focus-trap-react';
function Modal({ isOpen, onClose, children }) {
if (!isOpen) return null;
return (
<FocusTrap focusTrapOptions={{
initialFocus: '#modal-title',
escapeDeactivates: false, // Escape closes the modal below, which unmounts the trap
returnFocusOnDeactivate: true
}}>
<div role="dialog" aria-modal="true" onKeyDown={(e) => e.key === 'Escape' && onClose()}>
<h2 id="modal-title" tabIndex={-1}>Modal Title</h2>
{children}
<button onClick={onClose}>Close</button>
</div>
</FocusTrap>
);
}
For nested modals, such as a confirmation dialog inside a settings panel, you can set active={false} on the parent trap when the child opens, so only the child’s trap controls focus.
Benefits
- Keyboard navigation matches what users see, so if content looks blocked behind an overlay, keyboard users can’t move focus to it either.
- Keyboard users can’t accidentally press buttons that are hidden behind the overlay.
- The dialog pattern in the WAI-ARIA Authoring Practices says focus should stay inside the modal, so people who use assistive technology expect an accessible overlay to behave this way.
- Screen reader users stay inside the modal instead of ending up in background content they can’t see.
Tradeoffs
- Keeping track of focusable elements is complicated, because you need to handle disabled elements,
tabindex="-1", hidden elements, collapsed containers, and content slotted into a shadow root. The trap also breaks if you don’t query the list again when elements appear or disappear. - A focus trap without an obvious way out frustrates users, so the modal needs both Escape key handling and a visible close button.
- With nested modals, you have to keep careful track of which trap is active and which one should be paused when a child dialog opens.
- A focus trap only handles the Tab key, so a screen reader’s virtual cursor can still move outside it.
aria-modal="true"tells screen readers the background is inactive, but browsers and screen readers don’t all handle it the same way. - The
inertattribute disables background content properly and is now supported in all major browsers, so it’s usually a better choice than a hand-written trap if you’re building a new modal. - A library such as
focus-traphandles the edge cases but adds to your bundle size, and if you write your own trap, you have to handle all of those edge cases yourself. - Automated tests can check that focus wraps around, but not whether the modal is easy to use, so testing a focus trap properly means trying it with a keyboard and a real screen reader.
Summary
A focus trap keeps keyboard focus inside a container, so users can’t Tab out of a modal or overlay. A native <dialog> or the inert attribute does this without a trap, and a hand-written trap is for custom modals where you can’t use either. When the modal closes, your code returns focus to the element that opened it as a separate step. Keyboard and screen reader users can keep track of where they are, and they can’t accidentally use the content hidden behind the overlay.
See also
- Focus Management — Accessibility
- Keyboard Navigation — Accessibility
- ARIA Roles and Attributes — Accessibility
- Focus Trap Pattern
- focus-trap Library - GitHub
- Modal Dialog Accessibility - W3C