useTrapFocus allows you to trap focus inside a specific DOM element. Focus traps are especially useful for modals, dropdown menus, and other elements that should keep focus within the element when it is open.

This is a great way to improve the accessibility of your application because with focus traps, you can ensure that users navigating your site using only a keyboard won't accidentally interact with elements outside the focus trap.

Under the hood, this composable uses focus-trap/tabbable. To learn more about their specific implementation and see the rules used to gather focusable elements visit the tabbable docs (opens new window).


Base Usage

To use useTrapFocus, we can use a template ref to identify the element that we want to trap focus inside of. Then, we can pass that ref to useTrapFocus and whenever that element is being rendered, the focus trap will be active.

<script lang="ts" setup>
import { ref } from 'vue';
import { useTrapFocus } from '@storefront-ui/vue';

const focusTrapElementRef = ref<HTMLDivElement>();

  <div ref="focusTrapElementRef">
    This container has <a href="#">Focusable anchor</a> and another <button>Focusable button</button> or <span class="focus:outline" tabindex="0">Focusable span</span>