Skip to content

Instantly share code, notes, and snippets.

@narration-sd
Last active May 21, 2020 08:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save narration-sd/a10c5855cb0c06d562d7eb290b3251d3 to your computer and use it in GitHub Desktop.
Save narration-sd/a10c5855cb0c06d562d7eb290b3251d3 to your computer and use it in GitHub Desktop.
// ScrollMemNonEs6.js -- A small library to do own scroll memory positioning
// It's decomposed from an ES6-React module version, for proper use with Craft and Twig
function getPageKey () {
// this is tagged in a Gatsby-like way but our own variant, for clarity and lack of collisions
return '%%live-vue-pos' + '|' + window.location.pathname;
}
function holdPosition (e) {
window.sessionStorage.setItem(getPageKey(),
JSON.stringify([ window.scrollX, window.scrollY ]));
}
function scrollSetUpPositioning () {
window.addEventListener('unload', holdPosition);
}
function scrollTakeDownPositioning () {
window.removeEventListener('unload', holdPosition);
}
function scrollSetRememberedPosition () {
try {
const currentPosition = JSON.parse(window.sessionStorage.getItem(getPageKey()));
if (currentPosition && Array.isArray(currentPosition)) {
// uncomment for troubleshooting
// console.log('scrolling to: ' + JSON.stringify(currentPosition));
window.scrollTo(currentPosition[0], currentPosition[1]);
}
} catch (e) {
// uncomment for troubleshooting
// console.log('no currentPosition yet: ' + e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment