The Focus plugin for 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 Focus and x-trap Plugin
First, you will have to install the Focus plugin using either NPM or Yarn.
npm install @alpinejs/focus yarn add @alpinejs/focus
If you do prefer the CDN then use the script below.
<!-- Alpine Plugins --> <script defer src="https://unpkg.com/@alpinejs/focus@3.x.x/dist/cdn.min.js"></script> <!-- Alpine Core --> <script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
Step 2: Initialize the Focus Plugin
Next, you will have to initialize the Focus 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 focus from '@alpinejs/focus' Alpine.plugin(focus)
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>