javascript
51 lines · 8 steps
How to trap keyboard focus in a dialog
A focus trap keeps Tab navigation cycling inside a modal and restores focus when it closes.
Explained by
highlit
1const FOCUSABLE = [
2 'a[href]',
3 'button:not([disabled])',
4 'input:not([disabled])',
5 'select:not([disabled])',
6 'textarea:not([disabled])',
7 '[tabindex]:not([tabindex="-1"])',
8].join(',');
9
10export function trapFocus(dialog) {
11 const previouslyFocused = document.activeElement;
12
13 const getFocusable = () =>
14 Array.from(dialog.querySelectorAll(FOCUSABLE)).filter(
15 (el) => el.offsetParent !== null || el === document.activeElement
16 );
17
18 const handleKeydown = (event) => {
19 if (event.key !== 'Tab') return;
20
21 const focusable = getFocusable();
22 if (focusable.length === 0) {
23 event.preventDefault();
24 return;
25 }
26
27 const first = focusable[0];
28 const last = focusable[focusable.length - 1];
29 const active = document.activeElement;
30
31 if (event.shiftKey && (active === first || !dialog.contains(active))) {
32 event.preventDefault();
33 last.focus();
34 } else if (!event.shiftKey && active === last) {
35 event.preventDefault();
36 first.focus();
37 }
38 };
39
40 dialog.addEventListener('keydown', handleKeydown);
41
42 const initial = dialog.querySelector('[autofocus]') || getFocusable()[0] || dialog;
43 initial.focus();
44
45 return function release() {
46 dialog.removeEventListener('keydown', handleKeydown);
47 if (previouslyFocused instanceof HTMLElement) {
48 previouslyFocused.focus();
49 }
50 };
51}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A focus trap intercepts Tab and Shift+Tab at the boundaries to wrap focus back inside the container.
- 2Querying focusable elements live on each keypress keeps the trap correct as the DOM changes.
- 3Returning a cleanup function lets the caller undo listeners and restore prior focus in one call.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
python
from typing import Any, Sequence, Mapping def render_markdown_table(
Rendering an aligned Markdown table in Python
string formatting
data transformation
closures
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-to-trap-keyboard-focus-in-a-dialog-explained-javascript-70b0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.