When using live_link to navigate to a new page, the Y scroll position of the window is maintained.
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.
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!
Most helpful comment
Maintaining window's Y scroll position it's useful when clicking
live_link(or clicking a button with aphx-clickbinding) 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
and on your live view