0

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.

1 Answers1

0

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.