--- title: Element directives --- As well as attributes, elements can have _directives_, which control the element's behaviour in some way. ## on:_eventname_ ```svelte on:eventname={handler} ``` ```svelte on:eventname|modifiers={handler} ``` Use the `on:` directive to listen to DOM events. ```svelte ``` Handlers can be declared inline with no performance penalty. As with attributes, directive values may be quoted for the sake of syntax highlighters. ```svelte ``` Add _modifiers_ to DOM events with the `|` character. ```svelte
``` The following modifiers are available: - `preventDefault` — calls `event.preventDefault()` before running the handler - `stopPropagation` — calls `event.stopPropagation()`, preventing the event reaching the next element - `stopImmediatePropagation` - calls `event.stopImmediatePropagation()`, preventing other listeners of the same event from being fired. - `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so) - `nonpassive` — explicitly set `passive: false` - `capture` — fires the handler during the _capture_ phase instead of the _bubbling_ phase - `once` — remove the handler after the first time it runs - `self` — only trigger handler if `event.target` is the element itself - `trusted` — only trigger handler if `event.isTrusted` is `true`. I.e. if the event is triggered by a user action. Modifiers can be chained together, e.g. `on:click|once|capture={...}`. If the `on:` directive is used without a value, the component will _forward_ the event, meaning that a consumer of the component can listen for it. ```svelte ``` It's possible to have multiple event listeners for the same event: ```svelte ``` ## bind:_property_ ```svelte bind:property={variable} ``` Data ordinarily flows down, from parent to child. The `bind:` directive allows data to flow the other way, from child to parent. Most bindings are specific to particular elements. The simplest bindings reflect the value of a property, such as `input.value`. ```svelte