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
import { unstable_cache, revalidateTag } from 'next/cache' import { db } from '@/lib/db' export const getDashboardStats = unstable_cache(
Caching dashboard stats in Next.js
caching
cache-invalidation
tag-based-revalidation
Intermediate
8 steps
javascript
import { Component } from 'react'; import { reportError } from './services/telemetry'; export class ErrorBoundary extends Component {
How a React ErrorBoundary works
error-handling
lifecycle-methods
render-props
Intermediate
8 steps
javascript
function generateCalendarGrid(year, month) { const firstDay = new Date(year, month, 1); const lastDay = new Date(year, month + 1, 0); const daysInMonth = lastDay.getDate();
Building a text calendar in JavaScript
date-handling
grid-layout
modular-arithmetic
Intermediate
9 steps
php
<?php final class MarkdownParser {
Building a small Markdown-to-HTML parser in PHP
state-machine
parsing
closures
Intermediate
10 steps
javascript
function initScrollSpy() { const links = Array.from(document.querySelectorAll('.nav a[href^="#"]')); const sections = links .map((link) => document.querySelector(link.getAttribute('href')))
Building a scroll spy with IntersectionObserver
intersectionobserver
dom
event-driven
Intermediate
7 steps
python
from typing import Callable, Dict, Type class PluginRegistry:
A decorator-based plugin registry in Python
decorators
registry pattern
factory
Intermediate
9 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.