Tooltip in string – Svelte

Issue

Is it possible to pass the tooltip into a string of some variable in Svelte? I know that svelte has {@html expression} which works fine for basics like strong, h1 … but is there any way how to pass some class with tooltip into the text of a string.

Here is an example:

<script>

let description = 'some text where I need to pass the tooltip. Is it possible?';
    
</script>

{description} 

Solution

Like commented your question is a bit vague – but I guess you want to define a tooltip via a variable? Then this is how you could do this REPL

<script>
    import Comp from './Comp.svelte'

    let htmlStringWithTooltip = `
    <style>
    [data-tooltip] {
        position: relative;
    }
    [data-tooltip]:hover::before {
        content: attr(data-tooltip);
        position: absolute;
        left: 50%;
        transform: translate(-50%, -100%);
    }
    </style>
    <span data-tooltip='The tooltip'>Hello</span>
    `
</script>

<Comp {htmlStringWithTooltip} />

<style>

    :global(body) {
        padding-top: 3rem;  
    }

</style>
Comp.svelte
<script>

    export let htmlStringWithTooltip = ""

</script>

{@html htmlStringWithTooltip}

Answered By – Corrl

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.