Scrolling to an anchor when loading a LiveView page?

When visiting a non-LiveView page with a URL that contains a fragment, such as /non-live#foo, the browser will scroll to the element with name or id “foo” when the page loads (as expected).

When visiting a LiveView page with a similar URL, such as /live#foo, the browser does not scroll when the page loads, but I would like it to. I am able to get it to scroll by adding a Javascript event listener for phx:page-loading-stop, finding the element that matches the URL fragment, and then scrolling to that element using LiveView’s Browser.getHashTargetEl function and Javascript’s scrollIntoView function.

Has anyone else noticed this or found a different solution, or is it something that LiveView doesn’t (yet) support?

This is supposed to work (search for “scroll” in the changelog, similar past issues that have been since fixed). On what LV version are you?

3 Likes

I’m on 0.14.7, which is the latest LiveView as of today.

I generated a fresh LiveView project and reproduced the issue (in the “scroll-to-anchor” branch of the repo) in case anyone is interested.

If it’s supposed to work the way I described, I can file an issue.

What browser are you using? Your demo works fine for me.

The demo fails for me in Chrome 86.0.4240.11, Safari 14.0, and Edge 86.0.622.58. It works in Firefox 82.0.2. All on MacOS 10.15.7.

If I first load “localhost:4000/” and then add “#300” to the URL, it jumps there. But if I open a new window and paste in “localhost:4000/#300” then it doesn’t scroll.

(Also, in case it wasn’t clear, you need to check out the scroll-to-anchor branch of the repo and read the branch’s readme to see the things that work and don’t work for me.)

(Also also, thanks for trying it out @sfusato!)

In Firefox it works fine as is, I’ve now tested with Chrome also and it didn’t worked (I’m on Linux), but it seems that the HTML specs state that:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (“-”), underscores (“_”), colons (“:”), and periods (“.”).

I’ve added a letter at the beginning of the id and it looks like that was the cause as now it’s working in Chrome as well. Can you do that change and re-test?

1 Like

As of yesterday… today it’s 0.14.8 :slight_smile: