Restoring sticky live view scroll position during live redirects

Welcome!

Hmm, that’s odd – LiveView’s definitely gotten better at restoring scroll position out of the box in more recent versions, but it sounds like sticky/nested LiveViews might still be a problem.

Anyways, I’d probably stash scroll position on the client and restore it via a phx-hook on mounted rather than tracking it from the server since it’s a UI concern.

# pseudocode
Hooks.StickyNav = {
  mounted(){
    // stash scroll top
    this.el.addEventListener("scroll", e => {
      // consider debouncing
      sessionStorage.setItem("stickyNavScrollTop", this.el.scrollTop)
    })

   // restore scroll top
   scrollTop = sessionStorage.getItem("stickyNavScrollTop")
   if (scrollTop) { this.el.scrollTop = scrollTop }
  }
}

note: session storage is tied to an individual tab so local storage may be the way to go if you want to handle new tabs as well

And just a heads up, live_redirect has been deprecated for a good while now so it may be worth updating soon – especially with 1.0 around the corner!