Phx-target takes precedence over JS.push target?

Hi all,

in one of my live components I have something like:

<input
  id="foo"
  name="foo"
  type="text"
  phx-keydown={JS.push("foo_keydown", target: "#some-id")}
  phx-change="q_change"
  phx-target={@myself}
  value={@q}
/>

I would like for this input to fire the q_change event to itself and the foo_keydown to #some-id

But with that code, both events are dispatched to the component itself.

Am I doing something wrong?

Thank you

Does something like the following work?

<input
  id="foo"
  name="foo"
  type="text"
  phx-keydown={JS.push("foo_keydown", target: "#some-id")}
  phx-change={JS.push("q_change", target: @myself)}
/>

It seems like phx-target takes precedence over the target: option, so manually pushing each distinct event should resolve the issue. (Tested on my end and it works at least! :sweat_smile:)

If that doesn’t fix the issue, make sure your LiveComponent actually has the given ID #some-id - LiveComponent doesn’t automatically use the passed <.live_component id> as the DOM ID:

The given id is not automatically used as the DOM ID. If you want to set a DOM ID, it is your responsibility to do so when rendering:

defmodule UserComponent do
  use Phoenix.LiveComponent

  def render(assigns) do
    ~H"""
    <div id={"user-#{@id}"} class="user">
      <%= @user.name %>
    </div>
    """
  end
end

(You can verify by checking the browser devtools - LiveView will log a client-side error if the target ID doesn’t exist, i.e. nothing found matching the phx-target selector "#some-id".)

2 Likes

I ended up using the 2 JS.push. Thank you

1 Like