hotwire-livereload
hotwire-livereload copied to clipboard
Restore scroll position after reload
One way to solve the restore of the vertical scroll position after a reload.
function scrollToStoredPosition() {
let scrollPosition = localStorage.getItem("scrollPosition")
window.scrollTo(0, parseInt(scrollPosition))
}
function storePosition() {
localStorage.setItem("scrollPosition", window.scrollY)
}
document.addEventListener("turbo:before-visit", function (event) {
storePosition()
})
document.addEventListener("turbo:load", function (event) {
scrollToStoredPosition()
})
document.addEventListener("DOMContentLoaded", function (event) {
scrollToStoredPosition()
})
document.addEventListener("turbo:frame-load", function (event) {
scrollToStoredPosition()
})
window.onscroll = function (event) {
if (window.scrollY === 0) {
// It covers a mysterious edge case.
// Sometimes a page jumps to the top, fires the onscroll event and sets it to 0, when it shouldn't.
// This seems to do the trick.
scrollToStoredPosition()
} {
storePosition()
}
}
Put the code into app/javascript/application.js
or somewhere similar.
Thank you! I'll try it.
I pasted the code above in my applicaton.js but still not working. Scroll is moving up after each realod. What amb I missing?
Would be really nice if this feature would come out of the box as it is kind of expected.
@tomazzlender This worked, thanks.
I just removed the mysterious edge case hack because it would cause the screen to jump a bit when manually scrolling to the top of the page.
@tomazzlender Nice script. Only one question: The three addEventListener("turbo:... presumably require a locally installed script. Right?