0 day streak
javascript / beginner
Snippet

Conditional Classes with class:name

The class:name directive provides a clean way to toggle CSS classes based on a condition. If the expression inside the braces is truthy, the class is added; otherwise, it is removed.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
let active = false;
</script>
<button
class:active={active}
on:click={() => active = !active}
>
Toggle Status
</button>
<style>
.active { color: red; font-weight: bold; }
</style>
svelte
Breakdown
1
class:active={active}
Applies the 'active' CSS class only if the 'active' variable is true.