How to create a modal with Alpine.js

In this example, we have a <div>
element with an x-data
attribute that contains the modal's state (whether it is open or closed). The open
property is initially set to false
, which means the modal is closed by default.
Open modalModal titleModal content goes here
Close modal
Inside the <div>
element, we have a <button>
element that uses the @click
event directive to open the modal when clicked. The @click
directive is a shorthand for the x-on:click
attribute, and it sets the open
property to true
when the button is clicked, which causes the modal to open.
We also have a second <div>
element inside the <div>
with the x-data
attribute. This <div>
element contains the modal's HTML markup, and it uses the x-show
directive to show or hide the modal based on the value of the open
property. When the open
property is true
, the modal is shown, and when it is false
, the modal is hidden.
The second <div>
element also uses the @click.away
event directive to close the modal when the user clicks outside of it. This directive listens for a click event outside of the element and sets the open
property to false
when the event is triggered.
Inside the second <div>
element, we have a <h1>
tag for the modal's title, a <p>
tag for the modal's content, and a <button>
element that uses the @click
event directive to close the modal when clicked.
Finally, we include the Alpine.js library at the bottom of the page to enable the use of Alpine.js directives and events. The defer
attribute ensures that the script is loaded and executed after the page is parsed, which ensures that the modal is fully functional when the page is loaded.