'How do I keep the scroll bar at the same place is was before I left the website? Is it even possible? [duplicate]

My goal is that whenever the user closes and comes back to the website it recognizes where he/she was and automatically goes back to the topic the user was reading.



Solution 1:[1]

There may be a simpler way to do this, but this is the way I found most intuitive.

document.addEventListener("DOMContentLoaded", () => {
  // document has been loaded!
  if (localStorage.getItem("scrollY") !== null)
    window.scrollTo(0, localStorage.getItem("scrollY"));
});

document.addEventListener("scroll", () => {
  // user scrolled!
  localStorage.setItem("scrollY", window.scrollY);
});
  • You have the DOMContentLoaded event to the scroll on page load to the last position
  • You have the scroll event to update the scroll position in localStorage.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ares Stavropoulos