Classes
Like any other attribute, you can specify classes with a JavaScript attribute, seen here:
<button
class="{current === 'foo' ? 'active' : ''}"
on:click="{() => current = 'foo'}"
>foo</button>
This is such a common pattern in UI development that Svelte includes a special directive to simplify it:
<button
class:active="{current === 'foo'}"
on:click="{() => current = 'foo'}"
>foo</button>
The active
class is added to the element whenever the value of the expression is truthy, and removed when it's falsy.
App.svelte
xxxxxxxxxx
29
1
<script>
2
let current = 'foo';
3
</script>
4
5
<style>
6
button {
7
display: block;
8
}
9
10
.active {
11
background-color: #ff3e00;
12
color: white;
13
}
14
</style>
15
16
<button
17
class="{current === 'foo' ? 'active' : ''}"
18
on:click="{() => current = 'foo'}"
19
>foo</button>
20
Console
xxxxxxxxxx
110
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
null_to_empty,
13
run_all,
14
safe_not_equal,
15
space,
16
text
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
button.svelte-ecv9v0{display:block}.active.svelte-ecv9v0{background-color:#ff3e00;color:white}