useTrapFocus
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, useTrapFocus
uses focus-trap/tabbable
. To learn more about their specific implementation and see the rules used to gather focusable elements visit the tabbable docs.
Usage
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>();
useTrapFocus(focusTrapElementRef)
</script>
<template>
<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>
</div>
</template>