Feature: Restoring scroll position after reload (with code that does it)
One problem while developing a document is that after reloading the page the scroll position isn't restored. So if we tweak a certain part of a document, we always have to search for the last location in the book again.
Normally, browsers can restore the scroll position. But because paged.js
generates the content on the fly, it doesn't work here.
This is quite painful and kills productivity (especially, if we have to change things very often – as when we tweak the design of a component).
However, I wrote some code to fix this:
const pagedjs_scroll_pos = 'pagedjs-last-scroll-possition';
window.onbeforeunload = function(e) {
// Save last scroll possition:
localStorage.setItem(pagedjs_scroll_pos, window.scrollY);
};
class RestoreScrollPossition extends Paged.Handler {
constructor(chunker, polisher, caller) {
super(chunker, polisher, caller);
}
afterPreview(pages) {
const y = localStorage.getItem(pagedjs_scroll_pos);
if (y) {
// Just in case someone is wondering why the scroll possition is restored:
console.log("Paged.js: Restoring scroll possition");
window.scrollTo(0, y);
}
}
}
Paged.registerHandlers(RestoreScrollPossition);
This code can be added after the polyfill was loaded:
<script src="/js/paged_js_polyfill.js"></script>
<script>
$above_code
</script>
My code only stores the last Y (vertical) position, so the scroll position will not be correct if something before that position changes in height. But this is most likely still better than how it is now.
I'm wondering if this could be added to paged.js
, or if not, to the docs. I think it would be pretty useful.