Alpine.js: Events

The User Interface we define inside the browser is event-based. People do things on the page, like clicking buttons, and we react to those events with an event handler to do something.

You can use the @click attribute to listen for clicks:

<button @click="showThis = true">Show</button>

Click the button, and showThis turns to true, and the p tag is displayed:

@click is a shorthand for x-on:click.

The x-on attribute lets you define any kind of event, but I like the shorthand form more.

We have others like

  • @keyup
  • @keydown
  • @dblclick
  • @submit

We can use modifiers on the event listener to change the behavior.

For example it’s common sometimes to call event.preventDefault() when listening on a form submit event, to prevent the browser from sending the data to the server.

Something like:


const form = document.querySelector('form')
form.addEventListener('submit', event => {
  //..client-side logic...
  showThis = true

With Alpine we would write

<form @submit.prevent="showThis = true">

Much simpler, right?

I’ve also seen it used as @click.prevent to prevent the default behavior on link clicks.

One modifier I used was @click.outside to hide a modal when clicking outside of it.

I used something like this:

<div x-show="showModal" @click.outside='showModal = false'>
  ....the modal content

to the div containing the modal.

Another one I used was @keydown.enter to detect the “enter key” being pressed.

Another useful modifier is .window. Using it we can bind an event listener to the window, super useful for example to detect pressing the esc key to close a modal window:

  x-on:keydown.escape.window="showModalAddTask = false">

Without .window, you wouldn’t be able to detect the keypress because unless the user is focused on an input field, key press events are sent to the global window.

Lessons in this unit:

0: Introduction
1: Installing Alpine
2: The basics of Alpine
3: ▶︎ Events
4: Defining data
5: Looping
6: Binding user input to variables
7: Watching variables change
8: Stores