#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

Building a dropdown menu using Alpine.js

Last modified June 28th 2021 | GitHub Source Code [GitHub] | #alpine

Alpine 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>Code language: HTML, XML (xml)

With Alpine loaded create a wrapper <div> with the following attributes:

<div x-data="{ open: false }" x-on:click.outside="open = false">
  // ...
</div>Code language: HTML, XML (xml)

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>Code language: HTML, XML (xml)

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>Code language: HTML, XML (xml)

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}">&raquo;</span>
</button>Code language: HTML, XML (xml)

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:

Alpine.js code with class added

We can now apply some CSS to rotate the icon indicating the menu is open:

.rotated {
  transform: rotate(90deg);
  display: inline-block;
}Code language: CSS (css)

Finally we’ll add a transition so the opening and closing of the dropdown appears smoother:

<ul x-show="open" x-transition.opacity>
</ul>Code language: HTML, XML (xml)

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.

Related Posts

#AD Shop Web Developer T-Shirts