Timmy Lee
Timmy Lee

Reputation: 795

Toggle class on buttons in Svelte

Consider this Svelte code

{#each filters as filters, i}
   <div class='filter-container'>
      <div class='button filter' on:click={ () => setFilter(filters.name, filterContext)}>{filters.name}</div>          
   </div>
{/each}

The above filter buttons are made depending on how many filters there are in some js object. How can I create a class that is toggled for all filter buttons when the one button is clicked.

eg. when one is active all the others are not?

Upvotes: 1

Views: 3323

Answers (2)

Andreas Dolk
Andreas Dolk

Reputation: 114767

We can easily bind class names to expressions, so that the class will be added if the expression becomes truthy:

<script>
    let isActive = false
</script>

<style>
    .active {
        color: red;
    }
</style>

<h1 class:active={isActive}>Hello!</h1>
<button on:click={() => isActive = !isActive}>Click me</button>

Here, clicking the button toggles the isActive boolean. The class active is bound to that variable on the h1 element and you can see that the color now changes on every button click.

That is the standard way on how to set single classes dynamically.

REPL: https://svelte.dev/repl/988df145876a42c49bb8de51d2cae0f2?version=3.23.0

Upvotes: 4

Luca Fabbian
Luca Fabbian

Reputation: 215

Class are just strings - in svelte you can bind them to an expression as any other attribute.

For example:

<div class={'button filter ' + (activefilter === filters.name ? 'isactive' : '')}/>

when activefilter === filters.name is true, then the button class will became 'button filter isactive'

A special short syntax to toggle classes is provided too. Find more here

Upvotes: 4

Related Questions