javascript / beginner
Snippet
Dynamic Class Toggling
Svelte provides a shorthand for toggling CSS classes. Instead of manually manipulating the class string, you can use 'class:name={condition}' to add or remove a class based on a boolean value.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
<script>let active = false;</script><button on:click={() => active = !active}>Toggle State</button><div class:active={active}>Status: {active ? 'Active' : 'Inactive'}</div>
svelte
Breakdown
1
class:active={active}
Applies the 'active' CSS class only if the variable 'active' is true.
2
active = !active
Toggles the boolean value between true and false.