Phoenix_live_view: Window Y scroll position after following live_link is maintained

Created on 16 Nov 2019  路  5Comments  路  Source: phoenixframework/phoenix_live_view

Environment

  • Elixir version (elixir -v): 1.9.1
  • Phoenix version (mix deps): 1.4.10
  • Phoenix LiveView version (mix deps): 0.4.1
  • NodeJS version (node -v): 12.2.0
  • NPM version (npm -v): 6.9.0
  • Operating system: OSX Catalina 10.15.1

Actual behavior

When using live_link to navigate to a new page, the Y scroll position of the window is maintained.

Expected behavior

I was expecting the content of the page loaded via live_link to be scrolled to the top. Maybe maintaining the Y scroll position is the intended behaviour but it didn't seem very intuitive to me.

Most helpful comment

Maintaining window's Y scroll position it's useful when clicking live_link (or clicking a button with a phx-click binding) you update some content at the bottom of the page.

If you want to scroll the window to top you can use a JS hook. For example

// on app.js
let Hooks = {}
Hooks.ScrollToTop = {
    mounted() {
        this.el.addEventListener("click", e => {
            window.scrollTo(0, 0);
        })
    }
}
let liveSocket = new LiveSocket("/live", Socket, {hooks: Hooks})
liveSocket.connect()

and on your live view

def render(assigns)
  ~L"""
  <%= live_link "next", to: Routes.live_path(@socket, YouLiveView, @page + 1), 
                         phx_hook: "ScrollToTop" %>
   """
end

All 5 comments

Maintaining window's Y scroll position it's useful when clicking live_link (or clicking a button with a phx-click binding) you update some content at the bottom of the page.

If you want to scroll the window to top you can use a JS hook. For example

// on app.js
let Hooks = {}
Hooks.ScrollToTop = {
    mounted() {
        this.el.addEventListener("click", e => {
            window.scrollTo(0, 0);
        })
    }
}
let liveSocket = new LiveSocket("/live", Socket, {hooks: Hooks})
liveSocket.connect()

and on your live view

def render(assigns)
  ~L"""
  <%= live_link "next", to: Routes.live_path(@socket, YouLiveView, @page + 1), 
                         phx_hook: "ScrollToTop" %>
   """
end

Thanks for the issue and the hook is one way to solve it. I plan on investigating this in the near future to get us to a more robust place. There are a variety of cases one has to handle with this. I'll leave this issue open until then!

Thanks for the hook method @alvises. I agree it's useful with phx-click bindings, but I've been using live_link for page navigation, and in that instance, it seemed less intuitive.

Also related to #517.

fixed via ad96e91 . Thanks!

Was this page helpful?
0 / 5 - 0 ratings