An Interest In:
Web News this Week
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
Building a dropdown menu using Alpine.js
AlpineJS is a small JavaScript framework for composing behavior directly in HTML markup. In this tutorial Ill show you how the framework can be used to build a dropdown menu component. If youve 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/[email protected]/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
sets 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 thatll trigger the dropdowns visibility:
<button x-on:click="open = !open"> My Account</button>
Another x-on:click
this time were 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, lets add a couple of finishing touches to improve the look and feel. First lets add an icon thatll 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 youll 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 well add a transition so the opening and closing of the dropdown appears smoother:
<ul x-show="open" x-transition.opacity> ... </ul>
Thats all for this tutorial. As youve 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.
Original Link: https://dev.to/michaelburrows/building-a-dropdown-menu-using-alpinejs-47o3
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To