Hi, I'm a visual effects artist developing a website for my portfolio. I'm enjoying the challenge of web development and diving into svelte to do so.
I'm looking for a way to make things happen when the mouse is hovering over a given element.
I found this snippet of code in the Svelte REPL, which has the functionality I am looking for, which is great. But I'm actually really confused as to how it's working and wondering if someone can help me understand.
<script>
let active = false;
</script>
<style>
.active {
background:red;
}
</style>
<h1 class:active on:mouseenter={() => {
active = true;
}}
on:mouseleave={() => {
active = false;
}} >Hover or click me!</h1>
In this snippet of code it seems to me that the variable 'active', when set to true also sets the '.active' class to be true as well?
Basically if I set the variable 'active' to be any other name then the behavior stops working and I don't understand why.
I can't find any documentation that explains this, so hoping someone can shed some light on it for my confused noob brain.
The original snippet of code is a bit longer, and was grabbed from here: https://svelte.dev/repl/698309456ba84ec48dba0d7a29dd7faf?version=3.38.3
Top comments (1)
Hi! First of all, great to see more people trying out Svelte!
To the problem at hand:
The
class:active
is a short-hand forclass:active={condition}
where in this case the condition is also namedactive
. Another example to clarify could beclass:my-class={1 > 0}
where my-class would be set to the element if 1 is greater than 0.This is explained in two examples att svelte.dev as well:
svelte.dev/examples/classes
svelte.dev/examples/class-shorthand
For your sake, you would probably get faster answers from Sveltes official Discord
Have fun!