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)nonpassive
— explicitly setpassive: false
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 itselftrusted
— only trigger handler ifevent.isTrusted
istrue
. I.e. if the event is triggered by a user action.
You can chain modifiers together, e.g. on:click|once|capture={...}
.
App.svelte
9
1
2
3
4
5
6
7
8
›
⌄
⌄
<script>
function handleClick() {
alert('clicked');
}
</script>
<button on:click={handleClick}> Click me </button>
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
›
⌄
⌄
⌄
⌄
⌄
⌄
⌄
⌄
⌄
⌄
/* App.svelte generated by Svelte v4.2.19 */
import {
SvelteComponent,
detach,
element,
init,
insert,
listen,
noop,
safe_not_equal
} from "svelte/internal";
import "svelte/internal/disclose-version";
function create_fragment(ctx) {
let button;
let mounted;
let dispose;
return {
c() {
button = element("button");
button.textContent = "Click me";
},
m(target, anchor) {
insert(target, button, anchor);
if (!mounted) {
dispose = listen(button, "click", handleClick);
mounted = true;
}
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) {
detach(button);
}
mounted = false;
dispose();
}
};
}
function handleClick() {
alert('clicked');
}
class App extends SvelteComponent {
constructor(options) {
super();
init(this, options, null, create_fragment, safe_not_equal, {});
}
}
export default App;
result = svelte.compile(source, {
generate:
css:
});9
1
›
/* Add a <style> tag to see compiled CSS */