Skip to content

Why I use Alpine.js

New Course Coming Soon:

Get Really Good at Git

Alpine.js is a great little library to add “JavaScript sprinkles of interactivity”.

That’s what JavaScript was created for in the first place: add more life to HTML pages (rather than, for example, run in the browser an entire application framework used to render HTML).

Alpine is concerned with the client-side state, with tiny little bits of JS.

For example tracking the value of an input box, or opening a modal, etc.

You could also just use “vanilla” JavaScript DOM APIs for this, but for some things, Alpine simplifies a lot our job.

I like this a lot paired with server-side HTML generation using Astro, and client-server interactions handled through htmx. Alpine is the perfect fit for this stack.

But why do I use it?

Let me answer with practical examples of how I used it to solve problems.

One need I had was to close a modal defined in a dialog tag when I clicked outside of it.

Using vanilla JavaScript you’d have to do something like this:

function onClickOutside(element, callback) {
  document.addEventListener('click', (event) => {
    if (!element.contains(event.target)) {
      callback()
    }
  }, true)
}

const targetElement = document.querySelector('#yourElementId')

onClickOutside(targetElement, () => {
  document.querySelector('dialog').close()
})

You need to also come up with a good id name for your element, and think where to put this JavaScript.

With Alpine.js, all this JavaScript can be turned into 1 line you put directly on the element:

@click.outside.capture="document.querySelector('dialog').close()"

It’s much less code, it’s declarative, I don’t have to create an id I’ll use just for this, and the logic is local to the HTML element involved (LoB = Locality of Behavior).

Another example is showing/hiding a mobile menu when pressing a “hamburger” icon, kinda typical pattern.

With Alpine you define a showMenu var on a container element.

I’ll simulate the hamburger icon with a show/hide button.

<div
  x-data='{showMenu : false}'>
	<button
	  @click='showMenu = !showMenu'>
	  show/hide
	</button>
  <div x-show='showMenu'>
    ...the menu
  </div>
  ...the rest of your app
</div>

Click the button to show the menu content, click again to hide it.

Those were just 2 simple examples, but I hope you got the gist.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Read my Alpine.js Tutorial on The Valley of Code

Here is how can I help you: