How to restore scroll position in live view app?

yeah use live_patch…

now you might find yourself with the issue of the page not scrolling to top when navigation… eg scroll to bottom on first page and then navigate(live_patch) and find yourself on middle/bottom of new page (I did)
my app has in live.html.leex:
top_nav_component
wrapper_component
footer_component

where the wrapper then acts as kind of a router and renders the different pages…

first I just did a hook on the uri_path with a scroll to top - that worked when clicking links (live_patch) - but going back it be at the top - and forward at the top…

so I ended up putting a hook on all my live_patch links, that sets window.ready_to_scroll = true;:

<%= live_patch to: "#{@locale_prepend}/about", as: :about, replace: false, phx_hook: "ScrollToTop", class: "block sm:mr-4 sm:w-1/4" do %>
  link span/svg
    <% end %>
Hooks.ScrollToTop = {
  mounted() {
    this.el.addEventListener("click", e => {
      if (window.location.href == this.el.href) {
       window.scroll({
        top: 0, 
        left: 0, 
        behavior: 'smooth'
        });
      } else{
        window.ready_to_scroll = true;
      }

    })
  }
}

nb: that if it doesn’t navigate (eg I’m on /products and click on /products in the footer or top nav - I assume the user wants scroll to top)

then the uri_path hook (or in my case “active_page” since I don’t navigate on locale change - which changes the uri_path)

<span class="hidden" id="active_page" phx-hook="ChangeActivePage"><%= assigns[:active_page] %><%= assigns[:navigate_counter] %></span>

and the hook, notice the setTimeout… honestly can’t remember if it’s important :man_facepalming: :

Hooks. ChangeActivePage = {
  updated() {
    if (window.ready_to_scroll == true) {
      window.ready_to_scroll = false;
    
      setTimeout(function(){ 
       window.scroll({
          top: 0, 
          left: 0, 
          //behavior: 'smooth'
        });
       }, 30);
    }

  }
}

that way clicking links with live_patch scrolls to top - but going back/forward in browser doesn’t…

shoot me a DM and I can send you the link to the prod site for you to check out…

3 Likes