Jump to anchor tag on same page after submitting live view form

How is it possible to jump to an anchor tag on the same page after submitting a form with live view. E.g. in a live view file (…html.leex) I have a form like

<%= f = form_for @changeset, "#", [phx_submit: :save] %>
<label class="w3-text-grey" style="padding-left:8px;">Name</label>
<%= text_input f, :name, [class: "w3-input w3-hover-light-grey"] %>
<%= error_tag f, :name %>
<%= submit "Save", phx_disable_with: "Saving..." %>
</form>

and an anchor like

<h1 id="myanchor">Headline 1</h1>

How can I jump to this anchor after submitting the form? I tried to replace “#” in the form header with “#myanchor” but this is not working.

Any suggestions or ideas? Thx.

I know this question is quite old, but since it’s unanswered maybe this is still helpful to someone.

The way I handled this with LiveView is via a JS Hook. Here’s an example:

In JavaScript:

let hooks = {}
hooks.HandleScroll = {
  mounted() {
    this.handleEvent("scroll", ({to}) => location.hash = to)
  }
}
let liveSocket = new LiveSocket("/live", Socket, { hooks })

In the LiveView

def handle_event("submit", params, socket) do
  # do your normal thing, but also push_event
  {:noreply, push_event(socket, "scroll", %{to: "#runners"})}
end

In the LiveView template

<main>
  <%= f = form_for @changeset, "#", [id: "my-form", phx_submit: :submit, phx_hook: "HandleScroll"] %>
    <%# my form %>
    <%= submit "submit" %>
  </form>

  <div id="runners"></div>
</main>
3 Likes