Skip to main content

At the heart of Svelte is a powerful system of reactivity for keeping the DOM in sync with your application state — for example, in response to an event.

To demonstrate it, we first need to wire up an event handler. Replace line 9 with this:

<button on:click={incrementCount}>

Inside the incrementCount function, all we need to do is change the value of count:

ts
function incrementCount() {
count += 1;
}

Svelte 'instruments' this assignment with some code that tells it the DOM will need to be updated.

App.svelte
<script>
let count = 0;

function incrementCount() {
// event handler code goes here
}
</script>

<button>
Clicked {count}
{count === 1 ? 'time' : 'times'}
</button>

<style>
button {
width:200px;
}
</style>

/* App.svelte generated by Svelte v4.2.19 */
import {
SvelteComponent,
append_styles,
attr,
detach,
element,
init,
insert,
noop,
safe_not_equal
} from "svelte/internal";

import "svelte/internal/disclose-version";

function add_css(target) {
append_styles(target, "svelte-19benre", "button.svelte-19benre{width:200px}");
}

function create_fragment(ctx) {
let button;

return {
c() {
button = element("button");
button.textContent = `Clicked ${count} ${count === 1 ? 'time' : 'times'}`;
attr(button, "class", "svelte-19benre");
},
m(target, anchor) {
insert(target, button, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) {
detach(button);
}
}
};
}

let count = 0;

function incrementCount() {
} // event handler code goes here

class App extends SvelteComponent {
constructor(options) {
super();
init(this, options, null, create_fragment, safe_not_equal, {}, add_css);
}
}

export default App;
result = svelte.compile(source, {
generate:
css:
});
button.svelte-19benre{width:200px}