View Source
phx-
HTML attributes
A summary of special HTML attributes used in Phoenix LiveView templates.
Each attribute is linked to its documentation for more details.
Event Handlers
Attribute values can be:
Use phx-value-*
attributes to pass params to the server.
Use phx-debounce
and phx-throttle
to control the frequency of events.
Keyboard
Use the phx-key
attribute to listen to specific keys.
Example
lib/hello_web/live/hello_live.html.heex
<button type="button" phx-click="click" phx-value-user={@current_user.id}>Click Me</button>
<button type="button" phx-click={JS.toggle(to: "#example")}>Toggle</button>
lib/hello_web/live/hello_live.html.heex
<form phx-change="validate" phx-submit="save">
<input type="text" name="name" phx-debounce="500" phx-throttle="500" />
<button type="submit" phx-disable-with="Saving...">Save</button>
</form>
Socket Connection Lifecycle
lib/hello_web/live/hello_live.html.heex
<div id="status" class="hidden" phx-disconnected={JS.show()} phx-connected={JS.hide()}>
Attempting to reconnect...
</div>
DOM Element Lifecycle
lib/hello_web/live/hello_live.html.heex
<div
id="iframe-container"
phx-mounted={JS.transition("animate-bounce", time: 2000)}
phx-remove={JS.hide(transition: {"transition-all transform ease-in duration-200", "opacity-100", "opacity-0"})}
>
<button type="button" phx-click={JS.exec("phx-remove", to: "#iframe-container")}>Hide</button>
<iframe id="iframe" src="https://example.com" phx-update="ignore"></iframe>
</div>
Client Hooks
Client hooks provide bidirectional communication between client and server using
this.pushEvent
and this.handleEvent
to send and receive events.
lib/hello_web/live/hello_live.html.heex
<div id="example" phx-hook="Example">
<h1>Events</h1>
<ul id="example-events"></ul>
</div>
assets/js/app.js
let Hooks = {}
Hooks.Example = {
// Callbacks
mounted() { this.appendEvent("Mounted") },
beforeUpdate() { this.appendEvent("Before Update") },
updated() { this.appendEvent("Updated") },
destroyed() { this.appendEvent("Destroyed") },
disconnected() { this.appendEvent("Disconnected") },
reconnected() { this.appendEvent("Reconnected") },
// Custom Helper
appendEvent(name) {
console.log(name)
let li = document.createElement("li")
li.innerText = name
this.el.querySelector("#example-events").appendChild(li)
}
}
let liveSocket = new LiveSocket("/live", Socket, {hooks: Hooks})
Tracking Static Assets
lib/hello_web/components/layouts/root.html.heex
<link phx-track-static rel="stylesheet" href={~p"/assets/app.css"} />
<script defer phx-track-static type="text/javascript" src={~p"/assets/app.js"}>