Trigger CSS transitions from server side

I had a similar problem and managed to solve it without using hooks. In addition to pushing events to hooks, LiveView also dispatches events sent with push_event/3 to the window with a phx: prefix.

live_helpers.ex:

def push_js(socket, js \\ %JS{}) do
  cmd = Jason.encode!(js.ops) # LiveView expects this to be a string when we call `execJS` on the client

  socket
  |> push_event("exec_js", %{id: socket.id, cmd: cmd})
end

app.js:

window.addEventListener("phx:exec_js", (e) => {
  let el = document.getElementById(e.detail.id)

  liveSocket.execJS(el, e.detail.cmd)
})

Then in your LiveView, you can just do

def open(socket, id) do  
  socket
  |> push_js(show(id))
end

There might be a better way to do this, but I haven’t found one yet.

6 Likes