How to Preserve Scroll Position When Navigating Back With Javascript


By onjsdev

When navigating between pages on a website, it's important that user's scroll position is preserved. This provides a better user experience and allows users to quickly pick up where they left off.

In this article, we'll look at how to maintain scroll position with javascript when navigating back to the previous page in the browser.

Let's get started with saving scroll position.

Save Scroll Position

When the user navigates back, the browser restores the previous scroll position automatically. However, we can still override this behavior and restore the scroll position ourselves.

One way to do this is to use the popstate event to detect when the user navigates back and then restore the previous scroll position. Here's an example of how to preserve the scroll position using javascript when navigating in three steps:

Save scroll position when a link is clicked

By storing the window.pageYOffset value in the sessionStorage object, we can preserve the current scroll position even when the user clicks on a link that navigates to a new page.

document.querySelectorAll('a').forEach(function(link) {
  link.addEventListener('click', function() {
    sessionStorage.setItem('scrollPos', window.pageYOffset);
  });
});

Restore scroll position when navigating back

This code adds an event listener to the window object for the popstate event, which is fired when the user navigates backwards or forwards through their browsing history.

When the popstate event is triggered, the event listener checks whether the state property of the event object exists and whether it contains a scrollPos property. If both conditions are true, it uses the window.scrollTo method to scroll the page to the position specified by the scrollPos property.

window.addEventListener('popstate', function(event) {
  if (event.state && event.state.scrollPos) {
    window.scrollTo(0, event.state.scrollPos);
  }
});

Restore scroll position when the new page loads

This code is used to restore the user's previous scroll position when a new page is loaded.

// Restore scroll position when the new page loads
window.addEventListener('load', function() {
  var scrollPos = sessionStorage.getItem('scrollPos');
  if (scrollPos) {
    window.scrollTo(0, scrollPos);
    sessionStorage.removeItem('scrollPos');
  }
});

Conclusion

Protecting the scroll position when navigating between pages is an important part of providing a good user experience. We can use the popstate event to accomplish this.

Thank you for reading.