Events & Keyboard Handling

Handle DOM events with powerful modifiers.

Event Handling in Alpine

Alpine provides a clean and expressive way to listen to DOM events using x-on (or the shorthand @). You can listen to any native browser event and also custom events. The modifier system makes it unnecessary to write boilerplate code like event.preventDefault().

Click Events

Code
<button @click="open = true">Open</button>
<button @click.once="alert('This fires only once')">One-time click</button>

Keyboard Events

Keyboard shortcuts are easy. You can combine key modifiers with system modifiers to listen for specific key combinations.

Code
<input @keyup.enter="search()" placeholder="Search...">
<button @keydown.escape="closeModal()">Close</button>
<textarea @keydown.ctrl.s.prevent="save()">Ctrl+S to save</textarea>

Custom Events and $dispatch

Alpine's event system allows you to create your own events for communication between components.

Code
<!-- Child -->
<button @click="$dispatch('item-added', { id: 1 })">Add Item</button>

<!-- Parent -->
<div @item-added="handleAdd($event.detail)">...</div>

Window and Document Events

You can easily listen to events on the window or document objects using the .window and .document modifiers. This is great for global keybindings or scroll tracking.

Code
<div @keydown.window.escape="open = false">...</div>
<div @scroll.window.throttle.100ms="handleScroll">...</div>

Modifiers Reference

  • .prevent – calls event.preventDefault().
  • .stop – calls event.stopPropagation().
  • .once – fires only once.
  • .passive – for better scroll performance.
  • .self – only if event.target is the element itself.
  • .window – listen on window.
  • .document – listen on document.
  • .debounce.300ms – debounce the handler.
  • .throttle.200ms – throttle the handler.
How do I pass additional arguments to an event handler?

You can include them directly in the expression: @click="handle(item, $event)". The $event variable holds the native event object.

Live Click Counter

Helpful? Share this page!↑ Back to top