Events ====== Alpine makes it simple to listen for browser events and react to them. [Listening for simple events](#listening-for-simple-events) ----------------------------------------------------------- By using `x-on`, you can listen for browser events that are dispatched on or within an element. Here's a basic example of listening for a click on a button: As an alternative, you can use the event shorthand syntax if you prefer: `@`. Here's the same example as before, but using the shorthand syntax (which we'll be using from now on): In addition to `click`, you can listen for any browser event by name. For example: `@mouseenter`, `@keyup`, etc... are all valid syntax. [Listening for specific keys](#listening-for-specific-keys) ----------------------------------------------------------- Let's say you wanted to listen for the `enter` key to be pressed inside an `` element. Alpine makes this easy by adding the `.enter` like so: You can even combine key modifiers to listen for key combinations like pressing `enter` while holding `shift`: [Preventing default](#preventing-default) ----------------------------------------- When reacting to browser events, it is often necessary to "prevent default" (prevent the default behavior of the browser event). For example, if you want to listen for a form submission but prevent the browser from submitting a form request, you can use `.prevent`:
You can also apply `.stop` to achieve the equivalent of `event.stopPropagation()`. [Accessing the event object](#accessing-the-event-object) --------------------------------------------------------- Sometimes you may want to access the native browser event object inside your own code. To make this easy, Alpine automatically injects an `$event` magic variable: [Dispatching custom events](#dispatching-custom-events) ------------------------------------------------------- In addition to listening for browser events, you can dispatch them as well. This is extremely useful for communicating with other Alpine components or triggering events in tools outside of Alpine itself. Alpine exposes a magic helper called `$dispatch` for this: