Scroll
SPAish 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.
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
spaish.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/@wolframkriesing/spaish@1.0.5/_dist/spaish.min.js"></script>
<script>
spaish.scroll.restore('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:
spaish.scroll.restore('my-page-key', [
'#sidebar',
'.content-area',
'[data-scrollable]'
]);
Both window and element scroll positions will be preserved.
Storage
Scroll positions are stored in sessionStorage
using the provided page key:
- Key format:
{pageKey}---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
beforeunload
event to capture scroll positions - Automatically sets
history.scrollRestoration = 'manual'
to prevent conflicts - Invalid selectors are safely ignored
- Missing elements at restore time are skipped