Page scroll position not reset to top on navigation (regression)
See original GitHub issueDescribe the bug
When navigating to a new page, if you are already scrolled partway down the page, the next page load will keep the current scroll position and not scroll back to the top.
I believe this broke with next-193. When I install next-192, this does not happen – navigating to a new page always scrolls to the top, just like regular browser navigation.
Reproduction
Init the SvelteKit demo project. Add the following paragraph in about.svelte
after the last paragraph.
<p>Go <a href="/">home</a></p>
Make the browser window small enough so that the page scrolls and scroll to the bottom of the page. Click the Home link. The Home page loads, but does not scroll to the top (i.e. the nav bar is not visible).
.
Tested in Chrome and Firefox on Windows 10.
Logs
No response
System Info
System:
OS: Linux 4.19 Ubuntu 20.04.1 LTS (Focal Fossa)
CPU: (4) x64 Intel(R) Core(TM) i7-6600U CPU @ 2.60GHz
Memory: 7.79 GB / 12.40 GB
Container: Yes
Shell: 5.0.17 - /bin/bash
Binaries:
Node: 14.17.0 - ~/.nvm/versions/node/v14.17.0/bin/node
Yarn: 1.22.5 - /usr/bin/yarn
npm: 8.1.1 - ~/.nvm/versions/node/v14.17.0/bin/npm
Browsers:
Chrome: 89.0.4389.90
npmPackages:
@sveltejs/kit: ^1.0.0-next.193 => 1.0.0-next.193
svelte: ^3.34.0 => 3.44.1
Severity
serious, but I can work around it
Additional Information
No response
Issue Analytics
- State:
- Created 2 years ago
- Reactions:17
- Comments:51 (13 by maintainers)
These are great comments! This was my situation and what worked for me:
I have two independently scrolling panels in the
__layout.svelte
file:The
sidebar
element contains the navigation and the<main>
element contains my content. (The content in the<main>
element is the part whose scroll position needs to be reset to the top when a user navigates to a new page.) The issue for me was when I would scroll down one page and then click on another page in the navigation, then the scroll position of the content in the<main>
element would remain scrolled down the page. Borrowing some of the ideas posted above, I was able to fix it by adding theafterNavigation
hook in my__layout.svelte
file, like this:Since the scroll position of the content in the
<main>
element is what needed to be reset, I referenced the<main>
element inside theafterNavigation
hook and reset its scroll position.I hope that helps someone else.
I created a reproduction repo that you can access here.
I uploaded a demo in Cloudflare Pages. Here is a demo functioning correctly. When you scroll to the bottom of the page and click on the link, you arrive at the top of the new page.
If I add the following css, the bug appears:
You can see a demo of the bug here. Now when we scroll to the bottom of the page, when we click the link we no longer arrive at the top of the new page, but stay somewhere in the middle.