Blog>
Snippets

Dynamic Content Scroll Restoration Handling

Provide a code snippet on handling scroll restoration when dynamic content loading changes the scroll height of the page, ensuring the scroll position is accurate.
window.history.scrollRestoration = 'manual';
Disable the browser's automatic scroll restoration to manually handle restoring scroll position.
let savedScrollPosition = 0;

window.addEventListener('beforeunload', function() {
  savedScrollPosition = window.scrollY;
  sessionStorage.setItem('scrollPosition', savedScrollPosition);
});
Save the current scroll position in sessionStorage when the user navigates away from the page.
window.addEventListener('load', function() {
  if (sessionStorage.getItem('scrollPosition')) {
    window.scrollTo(0, parseInt(sessionStorage.getItem('scrollPosition')));
    sessionStorage.removeItem('scrollPosition');
  }
});
On page load, retrieve the saved scroll position from sessionStorage and scroll to that position. Then remove the saved position to prevent unintended scroll restoration on subsequent loads.