dojap
How can I use JavaScript in Phoenix LiveView?
I am having troubles with running JavaScript inside Phoenix.
Things that work in a normal html file doesn’t seem to work from Phoenix LiveView templates.
I need some basic stuff to work and can’t find any tutorial or docs.
Thanks for any links.
Most Liked
tomkonidas
What you are looking for is Javascript Interop in the Phoenix LiveView docs.
edisonywh
That is not how Phoenix LiveView work, there’s a couple of great resources out there explaining the programming model (Chris has a great video on it, though I can’t remember which conference it was).
The rough outline is that, when a user visits a LiveView page, Phoenix sends down a bunch of HTML down the server, the client then connects to LiveView via WebSocket (powered by Phoenix Channels). Then, given that you have attributes like phx-click, these events are then sent to LiveView via websocket, and LiveView responds via websocket - as you can see, nothing is done “fully on browser” as you initially thought.
This is where the JS interops come in though, for example say things like a menu state where you don’t need to send things to backend, you can do it fully locally like you want with JS interops. There’s two ways to do this, either via LiveView’s hooks, or via external dependency like Alpine.
tomkonidas
So what you would do is set up a hook in your JS that your button will trigger, and then in the Hook (JS) you could access your cookie, do whatever you want, and push the result back to the LiveView to be handled.







