The HX-Trigger response header triggers client-side events when a response is received.
Basic Usage
Send a single event:
HX-Trigger: myEvent
By default, the event is dispatched on the element that made the request and bubbles. Use from:body when listening elsewhere.
Listen from markup with hx-on:
<div hx-on="myEvent from:body -> this.classList.add('updated')"></div>
Send multiple events:
HX-Trigger: event1, event2
Event Detail
Send event detail with a JSON object:
HX-Trigger: {"notification":"Hello World"}
Scalar values are available on detail.value:
<div hx-on="notification from:body -> alert(value)"></div>
You can also listen from JavaScript:
document.body.addEventListener("notification", (evt) => { alert(evt.detail.value); // "Hello World" });
Send multiple detail fields with a nested object:
HX-Trigger: {"notification":{"level":"info", "message":"Saved"}}
Each nested property is copied onto the event detail:
<div hx-on="notification from:body -> this.dataset.level = level; this.textContent = message"></div>
Send multiple events with detail by adding properties to the top-level JSON object:
HX-Trigger: {"notification":"Saved", "refreshList":true}
<div hx-on="notification from:body -> this.textContent = value; refreshList from:body -> this.dataset.refresh = value"></div>
Targeting Other Elements
Trigger an event on another element with target:
HX-Trigger: {"notification":{"target":"#notifications", "message":"Saved"}}
The target value is resolved as a selector. The event is dispatched on that element instead of the source element.
<div id="notifications" hx-on="notification -> this.textContent = message"></div>
This can update client-owned state while the response swaps normal HTML elsewhere:
HX-Trigger: {"cartUpdated":{"target":"#cart", "count":3}}
<div id="cart" data-count="0" hx-on="cartUpdated -> data.count = count"> Cart (<span :text="data.count"></span>) </div>
This example uses the hx-live extension.
Notes
Response headers are not processed on 3xx response codes. Return a 2xx status when using this header.