summaryrefslogtreecommitdiffstatshomepage
path: root/www/headers/x-ht-trigger.md
blob: 55f8b7e8cfc562103f3f91cdd1560a00e43a09ca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
---
layout: layout.njk
title: </> htmx - X-HX-Trigger
---

## `X-HX-Trigger` Response Header

The `X-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:

`X-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:

```javascript
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:

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

To handle this event you would write the following code:

```javascript
document.body.addEventListener("showMessage", function(evt){
    alert(evt.detail.value);
})
```

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:

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

And handle this event like so:

```javascript
document.body.addEventListener("showMessage", function(evt){
   if(evt.detail.level === "info"){
     alert(evt.detail.message);   
   }
})
```

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:

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

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