Posts Learn Components Snippets Categories Tags Tools About

Alpine JS Trap Plugin

Learn how to use Alpine JS trap plugin to conditionally trap focus inside an element.

Created on Sep 07, 2021


The Trap plugin of Alpine JS allows you to conditionally trap focus inside an element such as modal and dialog. In this snippet, you will learn how to add and use them in your project.

Step 1: Install Alpine JS Trap Plugin

First, you will have to install the trap plugin using either NPM or Yarn.
npm install @alpinejs/trap

yarn add @alpinejs/trap
If you do prefer the CDN then use the script below.
<!-- Alpine Plugins -->
<script defer src="[email protected]/dist/cdn.min.js"></script>
<!-- Alpine Core -->
<script defer src="[email protected]/dist/cdn.min.js"></script>

Step 2: Initialise Trap Plugin

Next, you will have to initialize the trap plugin like below but do note that you will have to set up webpack build system. If you are using Laravel then do use Laravel Mix.
import Alpine from 'alpinejs'
import trap from '@alpinejs/trap'

Use Alpine JS x-trap

Now you can use the "x-trap" directive anywhere within where "x-data" is called. 
Do note that x-trap accepts a JS expression. If the result of that expression is true, then the focus will be trapped inside that element until the expression becomes false, then at that point, focus will be returned to where it was previously.
<div x-data="{ open: false}">
    <button @click="open = true">Open Dialogue</button>
    <span x-show="open" x-trap="open">
        <p>The content of the dialogue</p>
        <input type="text" placeholder="Some input...">
        <input type="text" placeholder="Some other input...">
        <button @click="open = false">Close Dialogue</button>

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Alpine JS Trap Plugin