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}">>> </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>
-
\$\begingroup\$ Welcome to Code Review! I changed the title so that it describes what the code does per site goals: "State what your code does in your title, not your main concerns about it.". Feel free to edit and give it a different title if there is something more appropriate. \$\endgroup\$Sᴀᴍ Onᴇᴌᴀ– Sᴀᴍ Onᴇᴌᴀ ♦2023年01月27日 18:21:07 +00:00Commented Jan 27, 2023 at 18:21
-
\$\begingroup\$ @SᴀᴍOnᴇᴌᴀ Thank you. I think I discovered some way to make this code follow the declarative approach of svelte. Should I answer my own question? \$\endgroup\$Anm– Anm2023年01月27日 18:31:44 +00:00Commented Jan 27, 2023 at 18:31
-
\$\begingroup\$ You can, and I have done so on some of mine like this one. OPs are encouraged to answer their own questions. See also meta posts like Answering your own review as well as Self-answering questions without other answers \$\endgroup\$Sᴀᴍ Onᴇᴌᴀ– Sᴀᴍ Onᴇᴌᴀ ♦2023年01月27日 18:39:01 +00:00Commented Jan 27, 2023 at 18:39
1 Answer 1
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}>>></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>>></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">>></span> <slot />
</p>
-
\$\begingroup\$ Make sure to use
group-hover:inline-block
when going with the css approach if you want to add css animations \$\endgroup\$Anm– Anm2023年01月29日 05:16:48 +00:00Commented Jan 29, 2023 at 5:16