focus-trap demo

Return to the repository

In the demos below, you'll be able to tell that a focus trap is active because it will turn pink. You should also be able to tell because it will trap your focus!

When a trap is active, you can deactivate it by pushing its deactivate button or, if the demo allows, hitting Escape.

default behavior

Here is a focus trap with some focusable parts.

initial element, no escape

When this focus trap activates, focus jumps to a specific, manually specified element.

Also, in this demo the Escape key does not deactivate the focus trap. You must click the button.

Here is a focus trap with some focusable parts.

initially focused container

Initial focus is on the containing element, which has tabindex="-1" and no focus outline; so when you tab through the trap focus does not return to the container.

Also, clicking on an outside element automatically deactivates this trap.

hidden treasures

Focusable nodes are initially hidden and then revealed within the trap. Use Escape to exit.

nested

Nested focus traps.

tricky initial focus

In this focus trap, the single focusable button is hidden (the ones you see at first have tabindex="-1"). If you activate the trap in this state, the fallbackFocus option is used to focus the container. If, however, you first make the focusable button visible by clicking "show focusable button", that button will receive focus when you activate the trap.

input activation

Any change to the input content triggers automatic activation of the focus trap, without changing selection within the input.

Here is a focus trap with some focusable parts.

delay

focus-trap ensure that the placement of focus within the trap is slightly delayed, so the focused element does not capture the event that originated the activation of the focus trap. For example, the same Enter keystroke won't open and close this trap.

radio group

A default focus trap that contains a radio group. You should be able to change the radio group with the arrow keys, but Tab should only focus the active radio. (Notice that you need a checked radio in the group for things to work as expected.)

Radio group

iframe

This focus trap contains an iframe. You should be able to tab into and out of the iframe. But you need to have a focusable element before and after the iframe for things to work as expected.

Return to the repository