Scroll
PicoSPA allows you to store and restore scroll positions across page loads, maintaining the user's scroll position in both the window and specific scrollable elements.
Why? You may ask. For example for pages, where you have a "load more" button, or a filter that changes the content of the page, you want to keep the scroll position when the new page loads, so the user can continue reading where they left off. Other use cases might be "like", "subscribe", "add to cart" buttons that change the content of the page, but you want to keep the scroll position.
Try it Out 👏
1️⃣ Try first
- Click here to reload this page and see it will NOT be scrolled down automatically.
2️⃣ Try second
- ❌
If turned on
picospa.scroll.restore('demo-scroll')is called on page load which restores the scroll position of this page. - ❓ Click here to reload this page and see it will be scrolled down automatically. This feels like nothing is happening since the site loads so fast, but look at the browser tab or devtools, and you see the reload.
3️⃣ Try this too:
- Toggle it on/off, click the link to reload the page to get a feel for how it works.
- Navigate to other pages and come back here; you will see the scroll position is restored.
- Turn the scroll restoration off, scroll a bit and turn it back on, the scroll position will be restored immediately.
How To Use
Add the script to your page and call restore with a unique page key:
<script src="https://cdn.jsdelivr.net/npm/@pic0/spa@2026.1.12/_dist/picospa.min.js"></script>
<script>
picospa.scroll.restore({key: 'my-page-key'});
</script>
This will:
- Store the current scroll position before page unload
- Restore the scroll position when the page loads
- Disable browser's default scroll restoration
Scrollable Elements
You can also restore scroll positions for specific scrollable elements:
picospa.scroll.restore({key: 'my-page-key', otherNodes: [
'#sidebar',
'.content-area',
'[data-scrollable]'
]});
Both window and element scroll positions will be restored.
Storage
Scroll positions are stored in sessionStorage using the provided page key:
- Key format:
{key} - scroll.restore - Window scroll stored as
window - Elements stored by their CSS selector
- Only works within the same browser session
Important Notes
- Call
restore()immediately after page load for best results - Uses
beforeunloadevent to capture scroll positions - Automatically sets
history.scrollRestoration = 'manual'to prevent conflicts - Invalid selectors are safely ignored
- Missing elements at restore time are skipped