You can also declare event handlers inline:
<div on:mousemove="{e => m = { x: e.clientX, y: e.clientY }}">
The mouse position is {m.x} x {m.y}
</div>
The quote marks are optional, but they're helpful for syntax highlighting in some environments.
In some frameworks you may see recommendations to avoid inline event handlers for performance reasons, particularly inside loops. That advice doesn't apply to Svelte — the compiler will always do the right thing, whichever form you choose.
App.svelte
xxxxxxxxxx
16
1
<script>
2
let m = { x: 0, y: 0 };
3
4
function handleMousemove(event) {
5
m.x = event.clientX;
6
m.y = event.clientY;
7
}
8
</script>
9
10
<style>
11
div { width: 100%; height: 100%; }
12
</style>
13
14
<div on:mousemove={handleMousemove}>
15
The mouse position is {m.x} x {m.y}
16
</div>
Console
xxxxxxxxxx
81
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
attr,
6
detach,
7
element,
8
init,
9
insert,
10
listen,
11
noop,
12
safe_not_equal,
13
set_data,
14
text
15
} from "svelte/internal";
16
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
div.svelte-1eka6t0{width:100%;height:100%}