Skip to content
A Web Component wrapper that makes it easier to manage focus trapping
HTML JavaScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.gitignore
LICENSE
README.md
package-lock.json
package.json

README.md

Focus Trapper

A Web Component wrapper that makes it easier to manage focus trapping.

About

🚨 A quick note—this is totally experimental and I'd love some feedback.

One of the challenging things about building accessible UI components in handling keyboard navigation, especially managing focus in components like modal dialogs. The goal of Focus Trapper is to abstract some of that functionality into a declarative, easy-to-use Web Component.

Getting started

Import FocusTrapper.js into your project and register it as a customElement;

Focus trapper is available on npm or you can import it from jsDelivr if you just want to try it out in a script tag.

<script type="module">
  import FocusTrapper from 'https://cdn.jsdelivr.net/npm/focus-trapper@0.1.0/src/FocusTrapper.js';
  
  // Define the <focus-trapper></focus-trapper> custom element
  customElements.define('focus-trapper', FocusTrapper);
</script>

After you have defined the <focus-trapper> custom element you should be able to use it in your HTML.

<focus-trapper>
  <button type="button">Button one</button>
  <button type="button">Button two</button>
  <button type="button">Button three</button>
</focus-trapper>

By default the focus-trapper custom element won't do anything. To make it trap focus you'll need to add the trapped attribute. Once the trapped attribute is set in your markup, or the trapped property is set programmatically on an instance of an focus-trapper element, you'll be able to tab into the focusable content inside, but focus will always be moved from the last focusable element to the first and vice versa.

<focus-trapper trapped>
  <button type="button">Button one</button>
  <button type="button">Button two</button>
  <button type="button">Button three</button>
</focus-trapper>

Inspiration

The idea for this focus trapper component was inspired by the FocusTrapZone React component in the the Microsoft Fabric design system.

Known issues

🐛 So far these are the bugs I can find.

  • Using radio buttons breaks the focus trap if you tab through a set of them without making a selection.
You can’t perform that action at this time.