What is :target option for JS.push?

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