Search code examples
single-page-applicationscrolltosveltesvelte-3

Handle window.scrollTo on svelte on a single page application


How can i go to a window position after an update on my Repl example? When i scroll down and click on a card and go back to the main window it allways jumps to the top. I have tried to insert window.scrollTo on afterupdate and also beforeupdate, inside the OpenCard.svelte also inside the App.svelte but i cant figure it out. What would be the best solution for this?

Repl


Solution

  • There is more than one solution for this, because this is quite a lot of code for such a question.

    one solution would be to add this line to your showHome function

    function showHome() {
        visible = true;
        requestAnimationFrame(() => window.scrollTo(0,100)); // That's the line
      }
    

    HOW IT WORKS:

    The reason this solution works is because you condition the entire app on the visible variable, so after setting visible = true; the app hasn't updated yet, and therefore calling window.scrollTo immediately will just scroll before the refresh. thus putting it inside a requestAnimationFrame will wait for the next redraw of the DOM, making the scroll only after the DOM's update.

    Another solution would still require requestAnimationFrame, There's no avoiding it using. It will require to create a reactive statement like this:

    $: if (visible) requestAnimationFrame(() => window.scrollTo(0,100));
    

    That way your app will always know when to change the scroll based on your visible variable's value.

    I think you should go with the second solution, it's more stable on future changes.

    To learn more about requestAnimationFrame and how to use it: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame