--- title: Events --- In most applications, you'll need to respond to the user's actions. In Svelte, this is done with the `on:[event]` directive. ### Element events When used on an element, `on:click={handler}` is equivalent to calling `element.addEventListener('click', handler)`. When the element is removed, Svelte calls `removeEventListener` automatically. ```html

Count: {count}

``` ```json /* { hidden: true } */ { count: 0 } ``` For more complicated behaviours, you'll probably want to declare an event handler in your `

Count: {count}

``` ```json /* { hidden: true } */ { count: 0 } ``` ### Event handler modifiers While you can invoke methods like `event.stopPropagation` directly... ```html
...
``` ...it gets annoying if you want to combine that with some other behaviour: ```html
...
``` For that reason, Svelte lets you use *event modifiers*: - [`preventDefault`](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - [`stopPropagation`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) - [`passive`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters) — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so) - [`once`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters) — removes the listener after the first invocation - [`capture`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameter) > `passive` and `once` are not implemented in `legacy` mode The example above can be achieved with modifiers — no need for a separate event handler: ```html
...
``` ### Component events Events are an excellent way for [nested components](docs#nested-components) to communicate with their parents. Let's revisit our earlier example, but turn it into a `` component: ```html

Select a category:

{#each categories as category} {/each} ``` When the user clicks a button, the component will fire a `select` event, where the `event` object has a `category` property. Any component that nests `` can listen for events like so: ```html ``` ```html

Select a category:

{#each categories as category} {/each} ``` Just as `this` in an element's event handler refers to the element itself, in a component event handler `this` refers to the component firing the event. There is also a shorthand for listening for and re-firing an event unchanged. ```html ``` Since component events do not propagate as DOM events do, this can be used to pass events through intermediate components. This shorthand technique also applies to element events (`on:click` is equivalent to `on:click="fire('click', event)"`).