Timmy Lee
Timmy Lee

Reputation: 795

Toggle Classes in Svelte Component

Consider this Svelte code:

https://svelte.dev/repl/e3ea17e8e09044999bf7cb4bc882adea?version=3.19.2

How can I adjust this so that each button can be toggled independently? As you can see it currently toggles all of the buttons :(

Upvotes: 1

Views: 6749

Answers (3)

Brian F Leighty
Brian F Leighty

Reputation: 992

An alternative to either having to make a new component or creating a variable for tracking is to use the class that you want to toggle. As an example:

element.classList.toggle('className');

Upvotes: 0

Timmy Lee
Timmy Lee

Reputation: 795

So for those wanting a more in-depth answer to the above, I've created a svelte button component that allows toggling and opening of links at this REPL

https://svelte.dev/repl/c5b48ef759d045d08d17b5f11b74e82e?version=3.19.2

Enjoy!

Upvotes: 1

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

You have to maintain the state for each button like so:

<script>let active = {button1: false, button2: false, button3: false};</script>

<style>.active {background-color: #ff3e00; color: white;}</style>

<button class:active="{active.button1}" on:click="{() => active.button1 = !active.button1}">foo</button>
<button class:active="{active.button2}" on:click="{() => active.button2 = !active.button2}">bar</button>
<button class:active="{active.button3}" on:click="{() => active.button3 = !active.button3}">baz</button>

Upvotes: 7

Related Questions