x-bind: attributes and classes
The x-bind directive writes the value of an expression into an element's attribute and updates it when the data changes. This is how data drives href, disabled, src and, most of all, classes: a crossed-out finished task, an active tab, a highlighted error.
An attribute
The attribute name goes after the colon. The shorthand is just a colon in front of the name:
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<div x-data="{ id: 7 }">
<a x-bind:href="'/tasks/' + id">Full syntax</a>
<a :href="'/tasks/' + id">Shorthand</a>
</div>Both links point to /tasks/7 — hover over them and the address appears in the corner of the window. The rest of the course uses the short form.
Boolean attributes
Attributes such as disabled, checked and required are either present or absent. Alpine adds the attribute when the expression is true and removes it when it is false:
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<div x-data="{ title: '' }">
<input @input="title = $event.target.value" placeholder="New task">
<button :disabled="title === ''">Add</button>
</div>While the field is empty the button is disabled. Type one character and it turns on. $event is the event object; it has a lesson of its own.
Classes
For :class an object works best: the key is a class name, the value is a condition. The class is added when the condition is true:
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<style>
.done { text-decoration: line-through; opacity: 0.6; }
</style>
<ul x-data="{
tasks: [
{ id: 1, title: 'Buy milk', done: true },
{ id: 2, title: 'Call Oleg', done: false }
]
}">
<template x-for="task in tasks" :key="task.id">
<li class="task" :class="{ done: task.done }" @click="task.done = !task.done" x-text="task.title"></li>
</template>
</ul>The first task is crossed out. Clicking any row toggles its state. The regular class="task" attribute stays: Alpine merges it with the classes from :class.
Styles
:style also takes an object. Property names are written in camelCase or in quotes with a hyphen:
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<div x-data="{ progress: 40 }">
<div style="background: #ddd; height: 10px">
<div :style="{ width: progress + '%', height: '10px', backgroundColor: 'seagreen' }"></div>
</div>
<button @click="progress = Math.min(progress + 20, 100)">More</button>
</div>The progress bar is 40% full, and the "More" button extends it up to 100%.
Common mistake
Forgetting the colon: href="'/tasks/' + id". Without : the attribute is a plain one, and the browser gets the string as is — the link points to an address with quotes and a plus sign. When the value is an expression, the attribute needs : or x-bind:.