Gh05d
Gh05d

Reputation: 8982

How to do window.scrollTo(0,0) in Svelte

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?

Upvotes: 6

Views: 11492

Answers (3)

Nour Adel
Nour Adel

Reputation: 61

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>

Upvotes: 0

Gh05d
Gh05d

Reputation: 8982

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.

Upvotes: 1

voscausa
voscausa

Reputation: 11706

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.

Upvotes: 7

Related Questions