DEV Community

Florent Raffray
Florent Raffray

Posted on

Noob confounded by 'on:mouseenter' code example, please help...

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>
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
oliie profile image
Oliver Praesto

Hi! First of all, great to see more people trying out Svelte!
To the problem at hand:

The class:active is a short-hand for class:active={condition} where in this case the condition is also named active. Another example to clarify could be class: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!