The class directive

Like any other attribute, you can specify classes with a JavaScript attribute, seen here:

  1. <button
  2. class="{current === 'foo' ? 'active' : ''}"
  3. on:click="{() => current = 'foo'}"
  4. >foo</button>

This is such a common pattern in UI development that Svelte includes a special directive to simplify it:

  1. <button
  2. class:active="{current === 'foo'}"
  3. on:click="{() => current = 'foo'}"
  4. >foo</button>

The active class is added to the element whenever the value of the expression is truthy, and removed when it’s falsy.