Introduction to Alpine.js
Alpine.js adds small bits of behaviour to your HTML that happen entirely in the browser. Like HTMX, you use it by adding attributes to your HTML.
Here’s how it works:
- You give an element some state: a few values it remembers.
- You change the state when something happens, like a click.
- The page updates itself to match the state.
In goals 1 to 3, every click sent a request to the server, because something needed to be saved. This time, nothing needs saving. We only want to show or hide something on the page, so Alpine can do it in the browser.
We could. HTMX could ask the server for a version of the todo item with the description open. But that’s a trip to the server and back just to show some text the browser already has. When the change only matters to the person looking at the page, keep it in the browser.
1. Give an element some state
Use x-data to give an element some state. You write it as a JavaScript object:
<div x-data="{ open: false }">
...
</div>Now this <div>, and everything inside it, can use a value called open. It starts as false.
Each element with x-data gets its own separate state. If you have ten of these <div>s on a page, each one has its own open.
2. Change the state
Use x-on to run a bit of JavaScript when an event happens:
<div x-data="{ open: false }">
<button x-on:click="open = ! open">Toggle</button>
</div>x-on:clicklistens for clicks on the button.open = ! openflipsopen.!means “not”, sofalsebecomestrueandtruebecomesfalse.
You’ll often see @click instead of x-on:click. It’s a shorthand that does the same thing.
3. Let the page update itself
Use x-show to show an element only when something is true:
<div x-data="{ open: false }">
<button x-on:click="open = ! open">Toggle</button>
<p x-show="open">Now you see me!</p>
</div>When open is false, Alpine hides the <p>. When open becomes true, Alpine shows it again. You never tell Alpine to “show the paragraph”. You change open, and Alpine keeps the page in step with it.