Focus trapping,
done right.
A production-grade modal engine using WeakMap for
private state, inert for background lockout, proper
ARIA orchestration, scroll preservation, and correct focus
restoration across N stacked layers.
Live Demos
Basic modal with focus trap, scroll lock, ARIA roles, and Escape key dismissal.
Open modal from inside a modal — focus correctly jumps between layers on close.
Modal with form, select, textarea. Tab cycles only within the modal boundary.
Destructive action dialog. role="alertdialog",
first focus on safe action.
Trigger button removed from DOM after click — focus still restored to nearest valid ancestor.
Opens 4 modals programmatically. Escape collapses them one by one, restoring focus each time.
Call the engine API directly from the console:
window.modalStack
modalStack.open(id)opens modal by id
modalStack.close(id?)closes top or by id
modalStack.closeAll()collapses entire stack
modalStack.getStack()returns ordered array
modalStack.onOpen(fn)lifecycle hook
modalStack.onClose(fn)lifecycle hook