How to add a class on click to Svelte inline?
<li on:click = {() => { this.classList.add('active'); }}>First</li>
The above is not working.
How to add a class on click to Svelte inline?
<li on:click = {() => { this.classList.add('active'); }}>First</li>
The above is not working.
this
is not bound in arrow functions.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.)
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.