5

I am using svelte and svelte-routing to create a website and try to scroll to the top of the page whenever a User navigates around. In other Frameworks like React window.scrollTo(0, 0) works perfectly fine. In Svelte, the following code does nothing unfortunately:

import { onMount } from "svelte";

onMount(() => window.scrollTo(0,0));

So what is the trick to make this work?

Gh05d
  • 7,923
  • 7
  • 33
  • 64
  • 5
    Please see [this](https://svelte.dev/repl/d1dee1c7ccaa4426878c8817fbc197e3?version=3.12.1) REPL, everything is working as expected, no? – Shaya Ulman Oct 10 '19 at 17:43
  • Yes, it works fine. So I must have some kind of bug in my code. I can't really think of anything. – Gh05d Oct 11 '19 at 08:02

3 Answers3

6

You can also bind to window properties like scrollX and scrollY using svelte window bind (API doc):

<svelte:window bind:scrollY={y}/>

Now you can read en set the y property. See this Svelte docs REPL.

voscausa
  • 11,253
  • 2
  • 39
  • 67
  • No, I already tried that and the y is always undefined. Maybe there is a problem with the routing packet I use (svelte-routing). – Gh05d Oct 11 '19 at 11:16
0

Okay, the bug was not a svelte problem. The issue was with the html styles. Seems like the overflow of the html was to be set on auto to work and not! on the body. Anybody also experiencing this bug can check out this thread.

Gh05d
  • 7,923
  • 7
  • 33
  • 64
0

Install the Svelte-scrollto package from npm. It helps with scrolling with animation.

npm i svelte-scrollto

then in your svelte file

<script>
 import * as animateScroll from "svelte-scrollto";
</script> 

<a on:click={() => animateScroll.scrollToBottom()}> Scroll to bottom </a>
<a on:click={() => animateScroll.scrollToTop()}> Scroll to top </a>
Nour Adel
  • 51
  • 3