Scroll to top of page in LiveView

I think this is a Routes.live_path/2, question. I have a two LiveView pages, index and show the index pages is quite long and may have hundreds of records requiring the user to scroll quite far. In some cases when users scroll down to the mid-way/bottom of all the records on the index page, when they click “view” to go to the show page the view loads scrolled super far down, much further than the content and they have to scroll to the top.
This is the link:

  live_redirect(name, to: Routes.live_path(socket, DesignLive.Edit, id))

This isn’t an issue I’ve been able to reproduce but I have at least one person who consistently has it in Chrome. Any thoughts?

@APB9785’s solution here is how I was planning on fixing this but I’m curious to know if there is another way without creating a hook?

1 Like

If I understand correctly you are using live_patch to navigate from index to show? According to the docs you should be using live_redirect when navigating to a different live view, not live_patch. The page should automatically scroll to the top then. live_patch is for patching new params to the current live view without tearing down and remounting, and is intended to maintain scroll position. Apologies if I misunderstood the question!

Sorry, I didn’t post the actual snippet, I’m using live_redirect with the Router live_path helper:

live_redirect(name, to: Routes.live_path(socket, DesignLive.Edit, id))

Ah ok, thanks for the clarification! The topic you referenced was regarding live_patch which is where my confusion came from. If you implement that JS hook, won’t it erase the scroll position history for all of your users? If so, that could negatively impact more people than the one person with the unreproducible bug. I also wonder if the bug is originating from the JS runtime of their browser anyway. Just a thought to consider :slightly_smiling_face:

Thanks for your thoughts.

I wouldn’t be be surprised if it was specific to their browser. I’m not sure how I could verify that other than having them switch browsers for the day.

As far as the JS hook goes, I would only use it on the page they are navigating too which generally isn’t much longer than view height and we want it to load at the top of the page anyway. Also, this is an admin panel so the user who is having the issue is one of about three people who has access to the page.

1 Like

Further investigation leaves me more puzzled…

I was playing around with BrowserStack this morning, and from what I can tell this is only on Windows machines (if BrowserStack is to be trusted), but the browser does not seem to matter, (Chrome, Edge, Firefox).

What makes things stranger is that window.scrollTo(0, 0) and window.scrollTo(top) don’t work on this page, even in the console.

So I’m wondering if the original issue and my hook with window.scrollTo(0, 0) not working are related issues, somehow.

const ScrollTopHook = {
  mounted() {
    window.scrollTo(0, 0)