1
\$\begingroup\$

This is my first time using svelte. I am also using tailwind and astro but that is irrelevant. The following component prepends >> to my text when it is being hovered upon and takes the >> out when it is not.

Is this the typical way to use svelte? Am I doing something wrong? I feel I am.

<script>
    let spanId = "selected";
    let isMouseOver = false;

    function handleMouseOver() {
        if(!isMouseOver) {
            this.innerHTML = `<span id="${spanId}">&gt;&gt; </span>` + this.innerHTML;
            isMouseOver = true;
        }
    }

    function handleMouseOut() {
        let selectedSpan = document.getElementById(spanId);
        selectedSpan.parentNode.removeChild(selectedSpan);
        isMouseOver = false;
    }
</script>

<p
    class="hover:text-green-600 cursor-pointer whitespace-nowrap"
    on:mouseover={handleMouseOver}
    on:mouseout={handleMouseOut}
>
    <slot />
</p>
\$\endgroup\$
3

1 Answer 1

3
\$\begingroup\$

As per some others in a community where I have asked:

A more idiomatic way of doing it in svelte would be to remove innerHTML completely. Svelte's declarative approach makes modifying the innerHTML property unnecessary.

function handleMouseOver() {
  isMouseOver = true;
}

And later in the markup just set the markup declaratively

<p
    class="hover:text-green-600 cursor-pointer whitespace-nowrap"
    on:mouseover={handleMouseOver}
    on:mouseout={handleMouseOut}
>
  {#if isMouseOver}
    <span id={spanId}>&gt;&gt;</span>
  {/if}  

   <slot />
</p>

Essentially the code turns to:

<script>
  let isMouseOver = false;
</script>

<p
    class="hover:text-green-600 cursor-pointer whitespace-nowrap"
    on:mouseover={() => (isMouseOver = true)}
    on:mouseout={() => (isMouseOver = false)}
>
  {#if isMouseOver}
    <span>&gt;&gt;</span>
  {/if}  

   <slot />
</p>

And also only CSS (tailwind in this case) could be used as so:

<p class="group hover:text-green-600 cursor-pointer whitespace-nowrap">
  <span class="group-hover:inline hidden">&gt;&gt;</span> <slot />
</p>
\$\endgroup\$
1
  • \$\begingroup\$ Make sure to use group-hover:inline-block when going with the css approach if you want to add css animations \$\endgroup\$
    – Anm
    Commented Jan 29, 2023 at 5:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.