Home / Snippets / Alpine JS Trap Plugin
Alpine JS Trap Plugin cover

Alpine JS Trap Plugin


2 years ago


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="https://unpkg.com/@alpinejs/[email protected]/dist/cdn.min.js"></script>
<!-- Alpine Core -->
<script defer src="https://unpkg.com/[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>
notion avatar


Week-end developer currently experimenting with web, mobile, and all things programming.






Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this