Hotwire Discussion

How to return the user to the top of the page after a 422 :unprocessable_entity response?

Some forms in my app take up a full page and any errors are returned as flash messages at the top of the page.

With turbolinks, submitting a form with errors results in the form re-rendering, with the user being taken back to the top of the page. However, with turbo, responding with a 422 doesn’t change the scroll position. Users will be left at the bottom of the page, perhaps not realising that the form has submitted and that there are errors they need to address.

Is there a way I can ensure the user is sent to the top of the page after a form re-renders with status 422?

Thank you!

1 Like

I think you’d need to hook up a stimulus controller. Something like this (untested):

# new.html.erb
<form data-controller="window" data-action="turbo:submit-end->window#scrollToTop">

# window_controller.js
scrollToTop() {
  window.scrollTo(0, 0)
}

(You could maybe also move the data-controller attribute up to the body, so the window_controller is always available.)

1 Like

Yay, this works! Thank you very much, dan! :blush: