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
<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.
<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.
<!-- 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.
<div @keydown.window.escape="open = false">...</div>
<div @scroll.window.throttle.100ms="handleScroll">...</div>Modifiers Reference
.prevent– callsevent.preventDefault()..stop– callsevent.stopPropagation()..once– fires only once..passive– for better scroll performance..self– only ifevent.targetis the element itself..window– listen onwindow..document– listen ondocument..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.