Svelte Transition Example: Fade out an element, alter its value then fade it back in

Link to the Svelte development page.

Svelte Transition Example: Achieve Smooth Visual Transitions by Fading Out an HTML Element, Applying Changes, and Fading It Back In

  • Create an object called opacity
JavaScript
    const opacity = tweened(1, {
        duration: duration,
        delay: 0,
    });

  • Inserts the value of opacity ($opacity) into the HTML
JavaScript
<div style="opacity:{$opacity}">{phraseText}</div>

  • Full Code
Svelte
<script>
    import { tweened } from "svelte/motion";

    let duration = 1000;
    let phraseText = "Phrase Generator";
    let phrases = [
        "1.. 2.. 3.. blast off!",
        "Huston, we have a problem!",
        "It's going to blow!",
        "Dammit Jim, I'm a doctor not a programmer!",
        "I think you should sit down for this...",
        "I can't do that Dave!",
        "Please don't press the any key!",
    ];

    const opacity = tweened(1, {
        duration: duration,
        delay: 0,
    });

    const getPhrase = () => {
        return phrases[Math.floor(Math.random() * phrases.length)];
    };

    const changePhrase = () => {
        opacity.set(0);

        setTimeout(() => {
            phraseText = getPhrase();
            opacity.set(1);
        }, duration);
    };
</script>

<div style="opacity:{$opacity}">{phraseText}</div>

<button
    on:click={() => {
        changePhrase();
    }}>Change Phrase</button
>