Why does LiveView scroll to top of page after submitting form?

Hello, I’m working on my first LiveView app. I’ve noticed that after submitting a form in LiveView, the page automatically scrolls to the top. I would like to instead preserve the current scroll position.

My use case is that the user might be editing something near the bottom of the page, and after saving the change, it’s confusing to end up at the top.

Here is an example of one of my forms:

    <.form for={@changeset} let={f} phx-submit={@action} class="p-4">
      <div class="flex flex-col mb-2">
        <%= hidden_input(f, :item_id, value: @item_id) %>
        <%= hidden_input(f, :is_collapsed, value: false) %>
        <%= label(f, :content) %>
        <%= textarea(f, :content, phx_hook: "AutoFocus", id: "entry-form", rows: @rows) %>
      </div>
      <%= submit("Save", phx_disable_with: "Saving...") %>
    </.form>

Thank you!

1 Like

Can you provide the event function that is handling this form when it is submitted?

Here is the update handler:

  @impl Phoenix.LiveView
  def handle_event("update_entry", %{"item_entry" => params}, socket) do
    case Board.update_item_entry(socket.assigns.editable_entry, params) do
      {:ok, entry} ->
        {:noreply,
         socket
         |> put_flash(:info, "Entry saved")
         |> push_redirect(to: Routes.board_show_item_path(socket, :show_item, entry.item_id))}

      _ ->
        {:noreply, put_flash(socket, :error, "Failed to save entry")}
    end
  end

I’m guessing it’s because of the push_redirect?

Yes I would say so. Because you’re redirecting to the same LiveView you can push_patch instead and move the code that loads the item from mount (runs when entering the LV first time/redirect) to handle_params (runs on live_patch), if you’re not doing that already.

Also depending on what you’re doing you can just update the assigns in place and avoid the redirect/patch.

2 Likes

That works great, thank you!

1 Like