Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

x-on and event modifiers

The x-on directive subscribes an element to an event — a click, input, a key press — and runs an expression when it happens. It replaces addEventListener from the "Events" lesson of the tutorial, but is written right in the markup.

A handler

The event name goes after the colon, the code goes in the value:

<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
 
<div x-data="{ count: 0 }">
  <button x-on:click="count++">Tasks added: <span x-text="count"></span></button>
</div>

Each click increases the number on the button.

The @ shorthand

x-on: is used so often that it has a short form — the @ sign. The value can also be a method call:

<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
 
<div x-data="{
  tasks: [],
  addTask() {
    this.tasks.push('Task ' + (this.tasks.length + 1));
    console.log(this.tasks);
  }
}">
  <button @click="addTask()">Add task</button>
</div>

After each click the console under the example prints the task array. The rest of the course uses the @click form.

Modifiers

A modifier goes after the event name with a dot and changes how the handler behaves:

ModifierWhat it does
.preventCalls preventDefault(), so a form does not reload the page
.stopStops the event from bubbling
.outsideFires on a click outside the element
.windowListens to the event on the whole window
.onceFires only once
.debounceWaits for a pause, 250 ms by default

The to-do form

Submitting a form with Enter and the .prevent modifier:

<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
 
<form x-data="{ tasks: [] }" @submit.prevent="tasks.push($refs.input.value); $refs.input.value = ''">
  <input x-ref="input" placeholder="New task">
  <button>Add</button>
  <p x-text="tasks.join(', ')"></p>
</form>

Type a task and press Enter or the button — it appears in the line below, and the page does not reload. x-ref and $refs give access to the field; they have a lesson of their own.

Keys

For keyboard events a modifier picks the key: @keydown.enter, @keydown.escape, @keydown.arrow-up.

<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
 
<div x-data>
  <input @keydown.escape="$el.value = ''" placeholder="Esc clears the field">
</div>

Type something and press Esc — the field is cleared. $el is the element the directive is on.

Common mistake

Forgetting .prevent on the submit event. The browser submits the form its own way and reloads the page, and all component data is lost — the task flashes and disappears. When Alpine handles a form, always write @submit.prevent.

Thanks for reading!

Donate to the site — we work hard for you.