Skip to content

Events & Attributes

In Svelte 5, DOM event handlers are regular attributes named like the property: onclick, oninput, onsubmit. You pass a function, exactly as you would in plain HTML/JS.

<script>
let count = $state(0);
</script>
<button onclick={() => count++}>+1</button>
<input oninput={(e) => console.log(e.currentTarget.value)} />

This is a deliberate change from Svelte 4, which used a special on:click directive. If you read older code or tutorials, you’ll see on:click={handler} — the modern equivalent is onclick={handler}. The new form is just a property, so it composes naturally and can be spread with other attributes.

When a variable has the same name as the attribute, use the shorthand {value}:

<script>
let src = $state('/logo.png');
let alt = $state('Logo');
</script>
<img {src} {alt} /> <!-- shorthand for src={src} alt={alt} -->

Spread a whole object of attributes with {...obj} — handy for forwarding props to an element:

<script>
let { ...rest } = $props(); // collect remaining props
</script>
<button {...rest}>click</button> <!-- forward them all to the button -->

Toggling classes and inline styles reactively is common enough that Svelte gives them dedicated directives.

class:name={condition} adds the class when the condition is truthy:

<div class:active={isActive} class:done={isDone}></div>

Svelte 5 also lets you pass an object or array to the plain class attribute (like the popular clsx helper):

<div class={{ active: isActive, done: isDone }}></div>

style:prop={value} sets an inline CSS property reactively:

<div style:color={textColor} style:font-size="{size}px"></div>

Both compile to precise updates — when isActive flips, only that class is toggled; when textColor changes, only that style property is set.

flowchart LR
  cls["class:active={isActive}"] --> u1["toggle exactly that class"]
  sty["style:color={textColor}"] --> u2["set exactly that CSS property"]
  ev["onclick={handler}"] --> u3["attach a plain event listener"]
Directives compile to surgical updates
How do you attach a click handler in Svelte 5?
What changed about events from Svelte 4 to Svelte 5?
What does `<img {src} {alt} />` mean?
What does `class:active={isActive}` do?