hotwire-livereload icon indicating copy to clipboard operation
hotwire-livereload copied to clipboard

Restore scroll position after reload

Open kirillplatonov opened this issue 3 years ago • 3 comments

kirillplatonov avatar Sep 03 '21 11:09 kirillplatonov

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.

tomazzlender avatar Jul 28 '22 21:07 tomazzlender

Thank you! I'll try it.

kirillplatonov avatar Aug 01 '22 05:08 kirillplatonov

I pasted the code above in my applicaton.js but still not working. Scroll is moving up after each realod. What amb I missing?

joanriba avatar Sep 19 '22 14:09 joanriba

Would be really nice if this feature would come out of the box as it is kind of expected.

n1xn avatar Dec 22 '22 21:12 n1xn

@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.

davidalejandroaguilar avatar Jan 13 '23 23:01 davidalejandroaguilar

@tomazzlender Nice script. Only one question: The three addEventListener("turbo:... presumably require a locally installed script. Right?

webdesignweisshart avatar Jul 15 '23 14:07 webdesignweisshart