Check out a free preview of the full Svelte course:
The "Classes Directive" Lesson is part of the full, Svelte course featured in this preview video. Here's what you'd learn in this lesson:

Rich demonstrates the class directive for adding and removing classes from an element.

Get Unlimited Access Now

Transcript from the "Classes Directive" Lesson

>> So just like any other attribute of a DOM element, you can set the class of an element using JavaScript inside curly braces. But this is such a common pattern that we have a special directive for classes specifically that allow you to toggle classes based on some condition.

[00:00:15] So instead of having current === 'foo' 'active' otherwise empty, we can just replace that whole thing with class:active = current === 'foo'. And we can get rid of those quotes, we're not asking anything. Apply that to all of those. And now the current class will, oops, I forgot to add the active.

[00:00:54] So now when we click on these, the active class, which adds this background style to the button, will get applied whenever this condition is true for each of the buttons in turn. And that's just less stuff to write. Just like with the bind value shorthand and source equal source shorthand that we've already encountered, you'll very often have a situation like this where the class that you're toggling is the same as the name of the condition.

[00:01:32] And so you have something like this class:big = big, which works like this. We can just get rid of the = big part of that, and spell it will fill in the blanks for us.