Hakim El Hattab tweeted a really nice little UX enhancement for a static site that includes a scrollable sidebar of navigation.
The trick is to throw the scroll position into localStorage
right before the page is exited, and when loaded, grab that value and scroll to it. I’ll retype it from the tweet…
let sidebar = document.querySelector(".sidebar");
let top = localStorage.getItem("sidebar-scroll");
if (top !== null) {
sidebar.scrollTop = parseInt(top, 10);
}
window.addEventListener("beforeunload", () => {
localStorage.setItem("sidebar-scroll", sidebar.scrollTop);
});
What is surprising is that you don’t get a flash-of-wrong-scroll-position. I wonder why? Maybe it has to do with fancy paint holding stuff browsers are doing now? Not sure.
These tricks that make your static site behave more like a single page “app” are great. This should work nicely with tools like turbolinks/quicklink.
If you want this trick to work in mobile browsers as well, you’re better off using the visibilitychange event instead of beforeunload (which doesn’t fire on mobile).
Might want to save the current time, too, and check it on reload. If the user comes back to your site a week later, she probably doesn’t want to jump to some random scroll point.
history.replaceState + history.state object + beforeunload event can be a cool approach too
CMIIW, it will be enabled to all pages. You may need to set namespace (for example, from the
location.pathname
) forlocalStorage
key to make sure that the scroll restoration will be applied only to that page.We also could add a notification bar at the top of the page allowing the user to choose if they want to scroll or not. Something like what Microsoft Word does when reopening a long document which had a non zero scroll position when it was closed.
Maybe you can try this code.
Hi, I’m kind of a noob and I’m really interested in this fonctionnality… I ried to put the code in the of my page between and but it does not seem to work…
Could someone provide me an example of how to use it ?
Regards :)