What is :target option for JS.push?

JS.push has this :target option without much explanation. I tried what it gives to server-side but nothing comes. I thought it might change target property on JS side, but I cannot figure out how does it work. What is it for?


Maybe that can help: Pushing Events: with and without JS.push · Fly

1 Like


So, :target comes from phx-target, not event.target in JS. It directs a server-side event to a Live state and not any DOM node.

JS.push() events go client --> server and you handle them in LiveView.handle_event/3 or LiveComponent.handle_event/3. You use the :target option to pick where the event is sent. You can target specifically a LiveComponent or you can target any DOM node with a query selector.

For instance in a LiveComponent, you might have something like the following:

<button phx-click={JS.push("clicked", target: @myself)}>click me!</button>

but you could also have for instance an id selector:

<button phx-click={JS.push("clicked", target: "#my-element")}>click me!</button>

In the second case the event will go to the LiveView containing an element #my-element.

Hope that helps!

1 Like