Alexander Zeitler

Listening to HTMX HX-Trigger response header events from Alpine.js

Published on Sunday, February 11, 2024

Photo by Vincent van Zalinge on Unsplash

Recycling

HTMX and Alpine.js are a great combination.

Here's how to listen to HTMX HX-Trigger response header events from Alpine.js.

HTMX allows you to listen for Events from the HTTP Response using the HX-Trigger response header (the last line matters) like this:

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Date: Sat, 10 Feb 2024 22:46:58 GMT
Server: Kestrel
Transfer-Encoding: chunked
HX-Trigger: product-added-to-shopping-cart

This indicates that a product has been added to the shopping cart.

HTMX itself can respond to this type of "events" like this:

<div hx-get="/shopping-cart-preview"
     hx-target="#shopping-cart-preview"
     hx-trigger="product-added-to-shopping-cart from:body"
     id="shopping-cart-preview"></div>

This will reload the shopping cart preview.

No we might want to display a toast or the like using Alpine.js when the product has been added.

HTMX is publishing the events it receives from the server as global events, so you can just listen to it from vanilla JavaScript:

<script type="text/javascript">
  document.addEventListener('product-added-to-shopping-cart', event => {
    console.log('product-added-to-shopping-cart')
  })
</script>

Alpine.js allows you to listen for events on the global window object like this:

<div @some-event.window="console.log('some-event was dispatched')">...</div>

So we can listen to product-added-to-shopping-cart using Alpine like this:


<div x-data="{showToast:false}"
     @product-added-to-shopping-cart.window="showToast = true">
    ...
</div>

Straight forward and simple, yet asked quite often.

What are your thoughts about "Listening to HTMX HX-Trigger response header events from Alpine.js"?
Drop me a line - I'm looking forward to your feedback! email
Imprint | Privacy