How to run animation only on first page visit

Viewed 438

on the sveltekit website I'm currently building I want to play a simple intro animation on the index page if it is the entrypoint to the app. If a user used the navigation to load the index page the animation should not play.

So i'm looking for a simple way to detect if a page is the entrypoint from that session or not.

Here is an example page with such functionality reed.be/

2 Answers

You could use SvelteKit's afterNavigate to detect where the current navigation came from. Only animate if it's not coming from another page on the same domain. Here is what the index page could look like:

<script>
    import { afterNavigate } from '$app/navigation';
    import { fade } from 'svelte/transition';

    // hide by default
    let visible = false;

    let duration;

    afterNavigate(({ from }) => {
        // only animate if the navigation came from outside the page
        duration = from === null ? 600 : 0;
        // toggle visbility in any case
        visible = true;
    });
</script>

{#if visible}
    <h1 in:fade={{ duration }}>Welcome to SvelteKit</h1>
{/if}

I assume you want to use in: with a custom transition. Since there are no ways (that I know of) to enable or disable a transition conditionally on an element, you could send a custom parameter to the transition function that indicates if it is the first load or not, and if it is you can enable or disable (i.e. set duration to 0 or something like that) the transition in the transition code itself. The first load variable could be a global store.

Not recommended but another way I see is to have two if blocks on the first load variable so you have two sets of the dom code but one is without the in: transition.

Related