Focus Trap Cycles Tab In Containers
Keep Tab cycling inside a container by listening for keydown and focusing the next or previous focusable, wrapping at both ends.
Code
// 焦点陷阱:Tab 在容器内循环,模态框用它防止焦点逃逸到底层页面
const container = document.createElement('div');
const first = document.createElement('button');
first.textContent = 'first';
const middle = document.createElement('input');
const last = document.createElement('button');
last.textContent = 'last';
container.append(first, middle, last);
const FOCUSABLE = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
function focusables() {
return [...container.querySelectorAll(FOCUSABLE)].filter((el) => !el.disabled);
}
function trapTab(event) {
if (event.key !== 'Tab') return;
const items = focusables();
const current = items.indexOf(document.activeElement);
event.preventDefault();
const step = event.shiftKey ? -1 : 1;
items[(current + step + items.length) % items.length]?.focus();
}
container.addEventListener('keydown', trapTab);
// Tab 到末尾:回绕到第一个;Shift+Tab 在开头:回绕到最后一个
last.focus();
last.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', cancelable: true }));
console.log('wrapped to first:', document.activeElement === first);
first.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, cancelable: true }));
console.log('shift-wrapped to last:', document.activeElement === last);The trap mechanics
trapTab listens for Tab on the container, collects focusables() via the FOCUSABLE selector (buttons, links, inputs, selects, textareas, non-negative tabindex), filters out disabled elements, and focuses items[(current + step + items.length) % items.length] — the modulo wraps in both directions.
Wrapping verified
The demo focuses last and dispatches a cancelable Tab KeyboardEvent: wrapped to first prints true because the wrap landed on first. Dispatching Shift+Tab on first prints shift-wrapped to last: true, proving the backward wrap.
preventDefault’s role
Calling event.preventDefault() stops the browser’s own focus move so the scripted wrap is the only navigation that happens — that is why the dispatched events must be cancelable.
Interactive Tools for This Topic
FAQ
- Why must the dispatched Tab events be cancelable?
- trapTab calls event.preventDefault() to stop the browser's own focus move; non-cancelable events cannot be prevented and the scripted wrap would race the default one.
- How does the modulo produce wrapping?
- current + step + items.length keeps the index non-negative before the modulo, so one past the end lands on 0 and one before the start lands on the last item.
Report a problem with this exampleOpens a pre-filled issue on GitHub.