Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 28 ยท Alpine.js Basics

Events, Modifiers and Refs

Handle events in Alpine.js with @ listeners and modifiers like .prevent, .outside and .debounce, reach elements with x-ref, and talk between components with $dispatch.

So far you have used @click to run a bit of code when a button is pressed. Real interfaces react to far more: key presses, clicks outside a menu, window resizes, form submits and events you invent yourself. Alpine handles all of them with the same @ attribute, and a small set of modifiers that replace the boilerplate you would otherwise write in JavaScript.

In this lesson you will listen to any event, shape that listener with modifiers (.prevent, .stop, .outside, .window, .debounce, .throttle, .once), react to specific keys, grab elements with x-ref, and send custom events between components with $dispatch. You should already know reactive state with x-data and forms.

Listening with @

@name="code" is shorthand for x-on:name="code". The name is any DOM event, and the code is an expression or a short statement list. Inside it you can use your component's data and a special variable, $event, which is the browser's event object.

Mouse position with $event

The listener sits on the element that receives the event, and the event bubbles up from children as usual, so you can also put one listener on a parent.

Event modifiers

A modifier is a word added after the event name with a dot. Modifiers can be chained: @click.stop.prevent.

Taming the event

.prevent Cancel the default action, like a link or submit.
.stop Stop the event bubbling to parents.
.self Only fire if this exact element was hit.
.once Run the handler a single time.
1 / 3

.prevent and .stop

.prevent calls event.preventDefault(). It is what you need on a link you want to handle yourself, or a form you do not want to reload the page. .stop calls event.stopPropagation() so parents never hear about the click.

.prevent and .stop

Click "Bubbles" and you get two log lines; click "Stopped" and you get one. The link would normally try to leave the page, but .prevent cancels that.

.outside, .window and .document

.outside runs your code when the event happens anywhere except inside the element. It is the standard way to close a dropdown or popup. .window attaches the listener to window, which is how you catch key presses or resizes that are not tied to one element.

Close a menu by clicking outside

The .outside listener is on the .menu wrapper, so clicks on the button or the panel count as inside.

@keydown.escape is only heard while focus is inside the element. To close a menu from anywhere, write @keydown.escape.window.

Debounce, throttle and once

.debounce waits until events stop coming for a while (default 250 ms), which suits search boxes. .throttle lets the handler run at most once per interval, which suits scrolling and resizing. .once removes the listener after the first call.

Debounce, throttle and once

Keyboard events

On keydown and keyup you can add a key name as a modifier: .enter, .escape, .space, .tab, .arrow-up, .arrow-down, .shift, or any single key like .a. Names are the kebab-case of event.key. Combine them with a dot for shortcuts: @keydown.ctrl.k.window or @keydown.shift.enter.

HTML
<input @keydown.enter="save()" @keydown.escape="cancel()">
<div @keydown.ctrl.k.window.prevent="openSearch()"></div>

On a Mac, .meta is the Command key. Keep keyboard handlers on elements that can really take focus, such as inputs and buttons, so that keyboard users get the same features as mouse users.

Reaching elements with x-ref

Sometimes you need the real DOM element, for example to focus an input. Mark it with x-ref="name" and read it as $refs.name anywhere inside the same component. $el is the element carrying the current directive.

Focus an input with $refs

After adding a tag, focus returns to the input so you can keep typing. $refs only sees elements inside the current x-data scope, and elements created later by x-if or x-for may not exist yet. See conditionals and loops for that timing issue.

Custom events with $dispatch

$dispatch('name', detail) fires a real DOM CustomEvent from the current element. It bubbles, so any ancestor can listen with @name, and the data arrives in $event.detail. This is the clean way for a child component to tell its parent something happened.

Because events bubble upward only, two sibling components cannot hear each other directly. The fix is .window: dispatch normally, and have the listener use @name.window.

flowchart LR
    A["Sender component<br/>$dispatch('saved')"] --> B["Event bubbles<br/>up to window"]
    B --> C["Listener component<br/>@saved.window"]

A custom event travels up to the window, where any component can hear it.

Two components talking by event

Event names should use kebab-case (item-added), because HTML attributes are case-insensitive and @itemAdded would be lower-cased by the browser. The same $dispatch is how Alpine will later trigger HTMX requests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which modifier runs a handler when the user clicks anywhere except inside the element?

    .outside fires for events that happen outside the element, which is ideal for closing dropdowns. .self means the event target was exactly this element.
  2. 2. How do you read the data sent by $dispatch('saved', { id: 5 }) in a listener?

    The second argument of $dispatch becomes the event's detail property, so the id is $event.detail.id.
  3. 3. Two sibling components need to hear the same custom event. What makes that work?

    Events bubble up, never sideways. A listener written as @name.window catches the event when it reaches the window.
  4. 4. What does @input.debounce.500ms do?

    Debounce waits for a pause. Throttle is the one that limits how often the handler can run.

Summary

  • @event (or x-on:event) attaches a listener; $event is the native event object.
  • Modifiers chain after a dot: .prevent, .stop, .self, .once, .outside, .window, .document, .debounce, .throttle.
  • Keyboard modifiers such as .enter, .escape and .ctrl.k make shortcuts easy.
  • x-ref plus $refs.name gives you a DOM element; $el is the current element.
  • $dispatch sends a bubbling custom event with data in $event.detail; use .window on the listener to cross between siblings.

Next, magic properties, x-effect and transitions.