Focus trap

Looping the Tab key inside an open modal so focus cannot wander to the page behind it, with Escape as the way out.

keeping tab stuck inside the popupnot tabbing behind the dialogfocus locktrap focusfocus trappingtab cycles inside the modalkeyboard stuck in the dialogstop tab from escaping the modal

See it

Live demo coming soon

What it is

While a modal is open, everything behind it should be untouchable. A focus trap enforces that for the keyboard: Tab from the last control inside wraps around to the first, Shift+Tab from the first wraps to the last, and focus never reaches the page underneath. Without one, a keyboard or screen reader user tabs straight 'through' the dialog into content they cannot see and cannot get back from. That is the classic broken modal.

The cheap way to get the containment right is to stop hand-rolling it: the native dialog element with showModal() puts the dialog in the top layer and makes the rest of the page inert, and the inert attribute on everything outside does that same containment job by hand. Be clear on what inert does not do, though. It does not move focus in on open, does not handle Escape, does not put focus back on close, and on its own it does not wrap Tab from the last control to the first (focus goes out to the browser's own chrome and comes back around). Those are still your code. Hand-rolled traps (query all focusable children, listen for Tab, wrap manually) break on hidden elements, disabled controls, negative tabindex, iframes, and shadow DOM, because no querySelector string covers all of those.

Gotcha: a trap without an exit is a cage. Escape must close the dialog, a visible close button must exist, and closing must return focus to whatever opened it. Also, only trap for genuinely modal surfaces. Tooltips, dropdown menus, and non-modal popovers should let Tab move on, not hold the user hostage.

Ask AI for it

Trap keyboard focus inside this modal while it is open. Prefer the native dialog element with showModal(), or set the inert attribute on every sibling of the modal outside it. Treat either one as containment only and write the rest yourself, because inert supplies no initial focus, no Escape handling, and no focus restoration. On open, move focus to the first focusable control inside; cycle Tab from the last control back to the first and Shift+Tab from the first back to the last; close on Escape and on the visible close button; restore focus to the element that opened the modal. Make the focusable-element query handle disabled, hidden, and negative-tabindex elements correctly. Do not trap focus on tooltips, dropdown menus, or other non-modal popovers.

You might have meant

modal dialog semanticsfocus managementkeyboard navigationaria hiddentab order

Go deeper