Return to a Scroll Position on Page Refresh

09-20-2020

I recently needed to “remember” my current position on a web page and wanted to automatically return to that position if there were a page refresh. I put together a simple solution that will track the window’s position and store the value in localStorage.

By adding the script snippet below to my webpage I can listen for the onscroll event on the window and update a localStorage item called scrollpos each time the onscroll event fires. There are probably times that we don’t want to return to the same scroll position, but this simple solution is a great starting point.

index.html

1
2
3
4
5
6
7
8
9
10
<script>
document.addEventListener("DOMContentLoaded", function (event) {
var scrollpos = localStorage.getItem("scrollpos");
if (scrollpos) window.scrollTo(0, scrollpos);
});

window.onscroll = function (e) {
localStorage.setItem("scrollpos", window.scrollY);
};
</script>