picospa.scroll
API for storing and restoring scroll positions across page loads for both window and specific scrollable elements.
restore()
Method signature: restore({key?: string, otherNodes? = []})
Stores current scroll positions before page unload and restores them on page load.
Parameters
key: string, optional- Unique identifier for storing scroll positions in sessionStorage, defaults tolocation.pathname.otherNodes: Array<string>, optional- Array of CSS selectors for additional scrollable elements. Additional, because thewindow's scroll offset is always stored by default. Defaults to[].
Description
The function sets up two main behaviors:
Storage (on beforeunload)
- Captures
window.scrollYposition - For each selector in
otherNodes:- Safely queries the DOM using try/catch
- Captures
scrollTopvalue for found elements - Stores as
[selector, scrollTopValue]pairs
- Creates a Map with
'window'and selector entries - Stores in sessionStorage using key
${key} - scroll.restore
Restoration (immediate)
- Sets
history.scrollRestoration = 'manual'to disable browser's default scroll restoration - Reads stored scroll positions from sessionStorage
- Restores
window.scrollYfor the window - Restores
scrollTopfor each matching element selector - Skips missing elements gracefully
DOM Requirements
windowobject must existhistory.scrollRestorationAPI support (gracefully handled if missing)- Selector elements should be scrollable containers with
scrollTopproperty - Elements matching selectors should exist when restoration occurs
Storage Details
- Uses
sessionStorage(persists only during browser session) - Storage key format:
${key} - scroll.restore - Stores as JSON serialized Map entries:
[['window', '123'], ['#sidebar', '456']] - Scroll positions stored as string numbers using
toFixed(0)
Example
// Basic usage - window scroll only
picospa.scroll.restore({key: 'my-page'});
// With additional scrollable elements
picospa.scroll.restore({key: 'docs-page', otherNodes: [
'#sidebar',
'.content-area',
'[data-scrollable="true"]'
]});
// Cross-page state with same key
picospa.scroll.restore({key: 'shared-layout', otherNodes: ['#navigation']});
Error Handling
- Invalid selectors are caught and ignored
- Missing elements during restoration are skipped
- Malformed storage data defaults to empty Map
- Non-numeric scroll values are handled by
parseInt()
Browser Events
- Uses
scrollendevent for (beforeunloadin Safari, which does not supportscrollend) - Executes restoration immediately when called
- Requires
sessionStoragesupport
Performance Notes
- Scroll positions are captured only once per page unload
- Restoration queries DOM once per selector
- Storage operations are synchronous