Vue Directive For Keyboard Navigation – KeyboardTrap

Keyboard Navigation is an important feature in website navigation because it improves user experience.

KeyboardTrap is a simple Vue 3/2 directive that enables keyboard navigation in your applications. The best part of this directive is that it prevents users from moving the focus away from a container or a component, which is called ‘Keyboard Trap’.

Basic Usage:

1. Import and register the directive.

// Vue 3
import { createApp } from 'vue';
import { VueKeyboardTrapDirectivePlugin } from '@pdanpdan/vue-keyboard-trap';
import App from './App.vue';
const app = createApp(App);
app.use(VueKeyboardTrapDirectivePlugin, {
  // options
// Vue 2
import Vue from 'vue';
import { VueKeyboardTrapDirectivePlugin } from '@pdanpdan/vue-keyboard-trap';
import App from './App.vue';
Vue.use(VueKeyboardTrapDirectivePlugin, {
  // options
new Vue({
  el: '#app',

2. Enable/disable the keyboard navigation on elements.

<div v-kbd-trap="directiveEnabled">

3. Available options.

app.use(VueKeyboardTrapDirectivePlugin, {
  // snake-case name of the directive (without `v-` prefix)
  name: 'kbd-trap',

  // CSS selector for focusable elements
  focusableSelector: [

  // CSS selector for elements that should not respond to roving key navigation
  rovingSkipSelector: [
    'select:not([disabled]) *',
    '[contenteditable]:not([contenteditable="false"]) *',
  // CSS selector that will be applied in .roving.grid mode to exclude elements - must be a series of :not() selectors
  gridSkipSelector: [

  // CSS selector for the elements that should be autofocused
  autofocusSelector: [

  // tabIndex value to be used when trap element has a tabIndex of -1 and has no `tabindex` attribute
  trapTabIndex: -9999,


Vue Directive For Keyboard Navigation KeyboardTrap


v1.0.19 (09/28/2023)

  • fix: do not set tabindex for dialog element

v1.0.18 (09/26/2023)

  • fix: activate trap if it’s enabled when focus is inside

v1.0.17 (01/27/2023)

  • feat: improve exit from inner to outer trap (when no focusable elements are after or before the inner trap

v1.0.16 (10/16/2022)

  • feat(autofocus): improve detection of visible/covered elements
  • feat(selectors): improve focusable elements default selectors

v1.0.15 (09/30/2022)

  • fix: add compatibility with Vue 2.7

Download Details:

Author: pdanpdan

Live Demo:

Download Link:

Official Website:

Install & Download:

# Yarn
$ yarn add @pdanpdan/vue-keyboard-trap

$ npm i @pdanpdan/vue-keyboard-trap

Add Comment