HX-Trigger Response Header

The HX-Trigger response header can be used to trigger client side actions from a response to htmx. You can trigger a single event or as many uniquely named events as you would like.

To trigger a single event with no additional details you can simply send the header like so:

HX-Trigger: myEvent

This will trigger myEvent on the triggering element and will bubble up to the body. As an example you could listen for this event like this:

document.body.addEventListener("myEvent", function(evt){
    alert("myEvent was triggered!");

If you want to pass details along with the event, you can move to JSON for the value of the trigger:

HX-Trigger: {"showMessage":"Here Is A Message"}

To handle this event you would write the following code:

document.body.addEventListener("showMessage", function(evt){

Note that the value of the message was put into the detail.value slot. If you wish to pass multiple pieces of data you can use a nested JSON object on the right hand side of the JSON object:

HX-Trigger: {"showMessage":{"level" : "info", "message" : "Here Is A Message"}}

And handle this event like so:

document.body.addEventListener("showMessage", function(evt){
   if(evt.detail.level === "info"){

Each property of the JSON object on the right hand side will be copied onto the details object for the event.

Finally, if you wish to invoke multiple events, you can simply add additional properties to the top level JSON object:

HX-Trigger: {"event1":"A message", "event2":"Another message"}

Using events gives you a lot of flexibility to add functionality to normal htmx responses.