AlpineJS is a small JavaScript framework for composing behavior directly in HTML markup. In this tutorial I’ll show you how the framework can be used to build a dropdown menu component. If you’ve never worked with Alpine before this will serve as a simple introduction to the framework.
For the purposes of this tutorial you can load the framework via CDN:
<script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
With Alpine loaded create a wrapper <div>
with the following attributes:
<div x-data="{ open: false }" x-on:click.outside="open = false">
// ...
</div>
x-data
defines a chunk of HTML as an Alpine component and provides data for that component to reference. x-on:click.outside
set’s the open data to false which will hide the dropdown when anywhere outside the component is clicked.
Next inside the wrapper <div>
add a button that’ll trigger the dropdown’s visibility:
<button x-on:click="open = !open">
My Account
</button>
Another x-on:click
this time we’re only tracking clicks directly on the button itself.
Now for the dropdown menu which is an unordered list with a x-show
attribute:
<ul x-show="open">
<li><a href="#">Edit Profile</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Log Out</a></li>
</ul>
When open
equals true
the x-show
attribute will change the visibility of the <ul>
element. At this point in the tutorial we have a basic functioning dropdown, let’s add a couple of finishing touches to improve the look and feel. First let’s add an icon that’ll represent the state of the dropdown menu:
<button x-on:click="open = !open">
My Account
<span :class="{'rotated': open}">»</span>
</button>
If you view the source code after the button has been clicked you’ll see the rotated class has been applied to the <span>
element:
We can now apply some CSS to rotate the icon indicating the menu is open:
.rotated {
transform: rotate(90deg);
display: inline-block;
}
Finally we’ll add a transition so the opening and closing of the dropdown appears smoother:
<ul x-show="open" x-transition.opacity>
...
</ul>
That’s all for this tutorial. As you’ve just seen by adding some simple Alpine attributes to HTML markup it relatively easy to create a functioning dropdown menu. With what you learnt in this tutorial you could also start building other UI elements with show/hide functionality and Alpine.js.
Top comments (1)
You could check the "menu" component in Vimesh Headless UI ( github.com/vimeshjs/vimesh-headless ), an alpinejs alternative of Tailwind Headless UI.