Scroll Restoration: Managing Scroll Position
What you'll learn: How to control whether the browser automatically restores scroll position when users navigate through history.
When you use the History API to navigate between states in a single-page application, the browser has a built-in behavior for handling scroll position. By default, modern browsers try to remember where you were scrolled on each page and restore that position when you use the back/forward buttons. This is great for traditional multi-page websites, but in single-page apps where you're managing navigation yourself with pushState and replaceState, you often want manual control over this behavior.
The scrollRestoration Property
The history.scrollRestoration property lets you choose between two modes:
'auto'(default): The browser automatically restores scroll position on navigation'manual': You take full control; the browser won't restore scroll position
Setting Scroll Restoration
// Let the browser handle scroll restoration (default)
history.scrollRestoration = 'auto';
// Take manual control
history.scrollRestoration = 'manual';
Why Use Manual Mode?
Think of it like an elevator: automatic mode remembers which floor you were on and returns you there. But in a single-page app where content changes dynamically, you might want the elevator to always start at the lobby (top of page) or go to a specific floor based on your own logic.
When you set manual mode, you can scroll to the top for new pages or restore custom positions stored in your state objects:
history.scrollRestoration = 'manual';
// Always scroll to top on navigation
window.addEventListener('popstate', () => {
window.scrollTo(0, 0);
});
Key Takeaway: Use history.scrollRestoration to control whether the browser or your code manages scroll position during history navigation—set it to 'manual' for full control in single-page applications.