DOM event handlers can have modifiers that alter their behaviour. For example, a handler with a once
modifier will only run a single time:
<script>
function handleClick() {
alert('no more alerts')
}
</script>
<button on:click|once={handleClick}>
Click me
</button>
The full list of modifiers:
preventDefault
— callsevent.preventDefault()
before running the handler. Useful for client-side form handling, for example.stopPropagation
— callsevent.stopPropagation()
, preventing the event reaching the next elementpassive
— improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)capture
— fires the handler during the capture phase instead of the bubbling phase (MDN docs)once
— remove the handler after the first time it runsself
— only trigger handler if event.target is the element itself
You can chain modifiers together, e.g. on:click|once|capture={...}
.
App.svelte
xxxxxxxxxx
9
1
<script>
2
function handleClick() {
3
alert('clicked')
4
}
5
</script>
6
7
<button on:click={handleClick}>
8
Click me
9
</button>
Console
xxxxxxxxxx
53
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
detach,
5
element,
6
init,
7
insert,
8
listen,
9
noop,
10
safe_not_equal
11
} from "svelte/internal";
12
13
function create_fragment(ctx) {
14
let button;
15
let mounted;
xxxxxxxxxx
53
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
detach,
5
element,
6
init,
7
insert,
8
listen,
9
noop,
10
safe_not_equal
11
} from "svelte/internal";
12
13
function create_fragment(ctx) {
14
let button;
15
let mounted;
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */
xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */