Blog>
Snippets

Handling Edge Cases in Scroll Restoration

Code example for dealing with edge cases such as handling hash-based scrolling and restoring scroll position after asynchronous data loading completes.
window.addEventListener('load', function() {
  // Check if the URL contains a hash
  if (window.location.hash) {
    const targetElement = document.querySelector(window.location.hash);
    if (targetElement) {
      // Scroll to the element associated with the hash
      targetElement.scrollIntoView();
    }
  }
});
This code listens for the window 'load' event and checks if the current URL contains a hash. If it does, it attempts to find the element with an ID matching that hash. If such an element is found, it uses the scrollIntoView method to scroll the element into view.
function restoreScrollPosition() {
  const scrollPosition = sessionStorage.getItem('scrollPosition');
  if (scrollPosition) {
    const { x, y } = JSON.parse(scrollPosition);
    window.scrollTo(x, y);
  }
}

function saveScrollPosition() {
  const scrollPosition = { x: window.scrollX, y: window.scrollY };
  sessionStorage.setItem('scrollPosition', JSON.stringify(scrollPosition));
}

window.onbeforeunload = saveScrollPosition;

// Example usage with async data loading
async function fetchData() {
  const data = await fetch('your-data-source-url');
  // Process your data...
  // After async operation completes, restore scroll position
  restoreScrollPosition();
}
This example contains functions for saving and restoring scroll position using session storage. The saveScrollPosition function captures the current scroll position and stores it before the page unloads. The restoreScrollPosition function retrieves and applies the saved scroll position. It includes an example integration with asynchronous data loading, where the scroll position is restored after the data loading operation completes.