2019-03-10 14:30:29 +01:00
|
|
|
---
|
|
|
|
title: The class directive
|
|
|
|
---
|
|
|
|
|
|
|
|
Like any other attribute, you can specify classes with a JavaScript attribute, seen here:
|
|
|
|
|
2023-04-02 17:24:33 +02:00
|
|
|
<!-- prettier-ignore -->
|
|
|
|
```svelte
|
2019-03-10 14:30:29 +01:00
|
|
|
<button
|
2023-04-02 17:24:33 +02:00
|
|
|
class={current === 'foo' ? 'selected' : ''}
|
|
|
|
on:click={() => current = 'foo'}
|
2019-03-10 14:30:29 +01:00
|
|
|
>foo</button>
|
|
|
|
```
|
|
|
|
|
|
|
|
This is such a common pattern in UI development that Svelte includes a special directive to simplify it:
|
|
|
|
|
2023-04-02 17:24:33 +02:00
|
|
|
<!-- prettier-ignore -->
|
|
|
|
```svelte
|
2019-03-10 14:30:29 +01:00
|
|
|
<button
|
2023-04-02 17:24:33 +02:00
|
|
|
class:selected={current === 'foo'}
|
|
|
|
on:click={() => current = 'foo'}
|
2019-03-10 14:30:29 +01:00
|
|
|
>foo</button>
|
|
|
|
```
|
|
|
|
|
2020-09-10 21:28:59 +02:00
|
|
|
The `selected` class is added to the element whenever the value of the expression is truthy, and removed when it's falsy.
|