\n```","keywords":"Scroll position, Local Storage","publisher":{"@type":"Organization","name":"Brian Childress Consulting","url":"https://brianchildress.co","logo":{"@type":"ImageObject","url":"/brian-childress-profile.jpg"}},"mainEntityOfPage":{"@type":"WebPage","@id":"https://brianchildress.co/blog/resume-page-position-on-refresh"}}

Return to a Scroll Position on Page Refresh

In this short article we'll take a look at a simple way to "remember" a scroll position on page refresh.

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

<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>