Scrolling to error messages outside of view? Listening to right event?

There’s an updated callback for client hooks that’s available alongside mounted and other lifecycle callbacks. The updated callback runs whenever “the element has been updated in the DOM by the server”. So if the parent form has phx-hook="ErrorScroll", the hook could be something like the below.

let Hooks = {}
Hooks.ErrorScroll = {
  updated() {
    // `this.el` references the parent form
    let firstError = this.el.querySelector("label.has-error");
    if (firstError) {
      firstError.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
    }
  }
}
let liveSocket = new LiveSocket("/live", Socket, { hooks: Hooks, ... })

Check out the Client hooks via phx-hook section of LiveView’s JavaScript interoperability docs for the entire list of callbacks as well as the attributes availiable to these callbacks.

1 Like