How do I stop default generated new/edit modals in Phoenix 1.7 from scrolling me to the top of the page when closed?

I tried this with a brand new generated Phoenix 1.7 app to make sure it wasn’t something I did. If I make a new app and then use to make a list of tasks, for example, when I finish editing or creating a task and the form modal closes, the browser always ends up scrolling to the very top of the page, instead of staying in the part of the list of tasks where I was before I opened the form modal.

Anyone know why this is or how to prevent it?


Seems the on_cancel={JS.navigate(~p"/<url>")} attribute in the resources’ generated index.html.heex is the culprit. It triggers a re-mount of the parent LiveView, hence the scroll position is lost.

For me, it’s fixed with on_cancel={JS.patch(~p"/<url>")}.

Update: should note that I wasn’t able to reproduce the behaviour when actually saving an entry (clicking “Save” button or pressing return), it only occurred for me when canceling out of the modal (clicking away or the “x” cancel button, pressing escape). I did notice that sometimes the scroll position was already reset as soon as the modal opened, but could not track that down.


Ooh I never would have found that; thank you! That seems to have resolved it for me.

Do you think this is worth reporting as a bug, or are there reasons navigate might make sense as the default behavior for others?

1 Like

Glad to hear! :slight_smile:

Not sure if this is a bug - re-mounting the LiveView also loads the latest entries from the DB. That means, when using patch here instead of navigate you could get stale data displayed. Though that would mean another user or background process is editing records as well - at which point you probably want to use PubSub anyhow?


That was fixed: on_cancel={JS.patch(~p"/<url>")} is the default now: Liveview traffic over the wire - #7 by chrismccord