Step 1: Install Alpine JS Trap Plugin
npm install @alpinejs/trap yarn add @alpinejs/trap
<!-- 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' Alpine.plugin(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> </span> </div>
Leave a reply