Focus Trapper Demo

The "trapped" attribute

Click the button to toggle the trapped attribute.

Dynamically add elements

This demo has focus trapping enabled by default. Click the button to add new elements after the page has loaded.

Modal dialog example

This example uses the native dialog element with a nested focus-trapper inside that wraps a form with a text input and a submit button as well as a button used to close the dialog.

Making the modal work

It's important to note that the native dialog element isn't implemented in all browsers. I've included a polyfill to add support, but the focus trapper should still work if you choose to implement your own custom modal dialog.

I've added a bit of JavaScript here to handle showing and hiding the modal, but the focus-trapper element does the rest.

With the trapped attribute added, the focus-trapper element will cycle focus from first to last focusable element in the dialog and vice versa. This keeps focus contained in the dialog per the requirements laid out in the ARIA Authoring Practices.