0

How to add a class on click to Svelte inline?

<li on:click = {() => { this.classList.add('active'); }}>First</li>

The above is not working.

jeff
  • 910
  • 2
  • 6
  • 25

2 Answers2

3
  1. this is not bound in arrow functions.
  2. You are not supposed to do that anyway.
    Use the class attribute with dynamic values or class:active={...}. The latter should ensure that the scoped styling still works properly without using :global().

(You are also not supposed to add click handlers on elements that are not buttons, it's inaccessible.)

H.B.
  • 166,899
  • 29
  • 327
  • 400
0

Here's one way you can do it:

<script>
  let clicked = false;
</script>
<li on:click|once={() => { clicked = true; }} class:active={ clicked }>First</li>
<style>
  li.active { color: red; }
</style>

The class: directive evaluates an expression and sets that class if true.

If the element is intended to be clicked just once, you can add the once modifier so it doesn't listen to subsequent click events.