how to store and restore web page scroll position?
- User
how to store and restore web page scroll position?
- Assistant
- User
not working
- Assistant
how to store and restore web page scroll position?
not working
To store and restore a web page's scroll position, you typically save the scroll coordinates (usually window.scrollX and window.scrollY) at a certain moment (e.g., before navigating away or when the user interacts) and then restore that position when the page is revisited or reloaded.
Here are some common techniques to achieve this:
sessionStorage or localStorageYou can store the scroll position in sessionStorage or localStorage before the user leaves the page, and restore it when the page loads.
Example:
// Save scroll position before unloading the page
window.addEventListener('beforeunload', () => {
sessionStorage.setItem('scrollPosition', JSON.stringify({
x: window.scrollX,
y: window.scrollY
}));
});
// Restore scroll position on page load
window.addEventListener('load', () => {
const scrollPos = sessionStorage.getItem('scrollPosition');
if (scrollPos) {
const { x, y } = JSON.parse(scrollPos);
window.scrollTo(x, y);
}
});
Notes:
sessionStorage if you only want the scroll position to persist within the current tab session.localStorage if you want the scroll position to persist across browser sessions (less common).If your app is SPA (React, Vue, Angular), you may want to track scroll positions per route:
const scrollPositions = {};
// When navigating away from a route, save scroll position
function saveScrollPosition(route) {
scrollPositions[route] = { x: window.scrollX, y: window.scrollY };
}
// When navigating to a route, restore scroll position
function restoreScrollPosition(route) {
const pos = scrollPositions[route];
if (pos) {
window.scrollTo(pos.x, pos.y);
} else {
window.scrollTo(0, 0); // default position
}
}
You can hook these to your route change events.
You can encode scroll position in the URL’s hash or query params on navigation and decode on page load.
Browsers have a native scroll restoration API you can control via JavaScript.
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual'; // or 'auto'
}
// You can then handle scroll restoration manually as above.
Basic storage and restore:
window.addEventListener('beforeunload', () => {
localStorage.setItem('scrollPos', window.scrollY);
});
window.addEventListener('load', () => {
const scrollPos = localStorage.getItem('scrollPos');
if (scrollPos !== null) {
window.scrollTo(0, parseInt(scrollPos, 10));
}
});
This is the simplest implementation that just stores vertical scroll.
If you want me to provide a snippet for a specific context (React app, Vue, etc.) or a more advanced solution, just ask!
If the simple approach of saving/restoring scroll position "on unload" and "on load" is not working, there could be several reasons:
load event such that scrolling to saved position won't work immediately.beforeunload might sometimes be unreliable).// Disable native scroll restoration in supported browsers
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
// Save scroll position periodically or on scroll event (debounced)
function saveScrollPosition() {
sessionStorage.setItem('scrollPosition', JSON.stringify({
x: window.scrollX,
y: window.scrollY
}));
}
// Use debounced saving on scroll to avoid performance issues
let saveTimeout;
window.addEventListener('scroll', () => {
clearTimeout(saveTimeout);
saveTimeout = setTimeout(saveScrollPosition, 200);
});
// Restore scroll position after page fully loads and content rendered
window.addEventListener('load', () => {
const scrollPos = sessionStorage.getItem('scrollPosition');
if (scrollPos) {
const { x, y } = JSON.parse(scrollPos);
// Delay scroll to ensure content has rendered.
setTimeout(() => {
window.scrollTo(x, y);
}, 100);
}
});
requestAnimationFrame or multiple delayed retries if your page content loads asynchronously (images, fonts, dynamic content).Example:
function restoreScrollTo(x, y, attempts = 0) {
if (attempts > 10) return; // Stop after 10 attempts
window.scrollTo(x, y);
// Check if scroll position is applied correctly — you can read back and compare
if (Math.abs(window.scrollY - y) > 5) {
requestAnimationFrame(() => restoreScrollTo(x, y, attempts + 1));
}
}
window.addEventListener('load', () => {
const scrollPos = sessionStorage.getItem('scrollPosition');
if (scrollPos) {
const { x, y } = JSON.parse(scrollPos);
restoreScrollTo(x, y);
}
});
Check if your content height is enough for the scroll position you want to restore. If the page content is short, scrolling to a large y value will have no effect.
For SPAs like React/Vue/Angular, store scroll position per route or trigger restore after route transitions.
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
const scrollPositions = {};
function ScrollManager() {
const location = useLocation();
useEffect(() => {
// Restore scroll position on route change after a short delay
const pos = scrollPositions[location.key];
setTimeout(() => {
if (pos) window.scrollTo(pos.x, pos.y);
else window.scrollTo(0, 0);
}, 100);
return () => {
// Save scroll position before leaving route
scrollPositions[location.key] = { x: window.scrollX, y: window.scrollY };
};
}, [location]);
return null;
}
history.scrollRestoration = 'manual'.If you want, I can help with a specific setup or share a working demo you can try. Just let me know!
Not yet included in a published release.