Back to Blog

Published: Jun 18, 2020

Tailwindcss dropdown with the use of Alpine.js

Hello, today I want to introduce you to a JavaScript framework: Alpine.js. Alpine.js is a small (~7KB gzipped) JavaScript framework with the same functionallities like JQuery, and a code syntax that is borrowed from Vuejs.

First, I am going to show the possibilities of the framework. Then, we are going to build a dropdown menu with the use of Tailwindcss and Alpine.js.

When to use Alpine.js

You should use Alpine.js if you don’t want to make a full SPA, but still need some JavaScript. Alpine.js perfectly integrates with Laravel Livewire and the rest of the TALL stack. Some functionallities of the framework:

You can also use it for a dynamic form, like showed in this tutorial from Chasing Code.

How to install Alpine.js

You can alpine.js from CDN by adding the following script to the end of your <head> section:

The package is also available from NPM. Run the following command to add Alpine.js: npm i alpinejs. Then you need to import it in your script: import 'alpinejs'.

If you are using Laravel you place it in the resources/js/bootstrap.js file.


Now it is time to see how easy it is to create a dropdown in Tailwindcss with the use of Alpine.js.

Checkout this tutorial, if you want to learn how to install Tailwindcss to your Laravel project.

Below is the JSFiddle with the code for the dropdown.

<iframe height="465" style="width: 100%;" scrolling="no" title="Dropdown" src=",result" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen Dropdown by larapeak (@larapeak) on CodePen. </iframe>

We create a button with Tailwindcss. The button has the relative class. With this class we can position the dropdown body absolute to the button.

Next we will add x-data="{ open: false }" attribute. This will initialize a variable open that we can use to check if the dropdown is open.

When we press the button, we need to open the dropdown body. We do this by adding x-on:click="open = true" to the button.

On the dropdown body we set a show attribute with an animation if the open variable is true. We do this by adding x-show.transition="open". If the user clicks away we want to close the dropdown body. We do this with the x-on:click.away="open = false" attribute.

That is it! We now have a fully working dropdown modal using Tailwindcss and Alpine.js.

Wrapping it up

I hope you enjoyed this post. Do you have any questions or suggestions? Please contact me on Twitter!!

Follow me on twitter to get notified when I post a new blog @larapeakdev