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:

<form>...</form>

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

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
</div>

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:

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

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
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. Launching May 21, 2024. Join the waiting list!