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! Ichanged the title so that it describes what the code does persite goals: "State what your code does in your title, not your main concerns about it.". Feel free toedit and give it a different title if there is something more appropriate.\$\endgroup\$2023-01-27 18:21:07 +00:00CommentedJan 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:00CommentedJan 27, 2023 at 18:31
- \$\begingroup\$You can, and I have done so on some of mine likethis one. OPs areencouraged to answer their own questions. See also meta posts likeAnswering your own review as well asSelf-answering questions without other answers\$\endgroup\$2023-01-27 18:39:01 +00:00CommentedJan 27, 2023 at 18:39
1 Answer1
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 theinnerHTML 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-blockwhen going with the css approach if you want to add css animations\$\endgroup\$Anm– Anm2023-01-29 05:16:48 +00:00CommentedJan 29, 2023 at 5:16
You mustlog in to answer this question.
Explore related questions
See similar questions with these tags.
