How can I retain the scroll position of a scrollable area when pressing back button?

During page unload, get the scroll position and store it in local storage. Then during page load, check local storage and set that scroll position. Assuming you have a div element with id element. In case it’s for the page, please change the selector 🙂

$(function() {
   $(window).unload(function() {
      var scrollPosition = $("div#element").scrollTop();
      localStorage.setItem("scrollPosition", scrollPosition);
   });
   if(localStorage.scrollPosition) {
      $("div#element").scrollTop(localStorage.getItem("scrollPosition"));
   }
});

Leave a Comment