Search code examples
csssapper

Sapper: CSS smooth scrolling for anchor links has unwanted impact on route links


In a Sapper application, I'm using CSS smooth scrolling for a better effect when navigating with anchor links within a given page (route):

html {
  scroll-behavior: smooth
}

However, this causes navigation to other routes to behave in an unwanted manner: instead of being reset to the top of the page, the scroll position remains unchanged from the previous route (in Firefox). (In Chrome, same thing, but the page then smoothly scrolls back to top.)

I understand that this is because of how Sapper works, but is there a known solution allowing to use CSS smooth scroll (for anchor links) while having route navigation work "as expected" and go directly to the top of the page on load?

Live example here: https://www.cinematheque.fr/henri/. html { scroll-behavior: smooth; } is commented out, you can activate it in the devtools. The block under the title is a bunch of anchor links.


Solution

  • You could try to create a function for anchor links that uses window.scrollTo to scroll to your element, this allows you to disable the html css directive that breaks your app

    I wrote this quick example : https://svelte.dev/repl/0a9f812027da4d99b253f39a1941986c?version=3.31.0