Search code examples
djangodjango-templatesalpine.jshtmx

Listening for HTMX events with Alpine.js in Django


Django templates can listen for events from HTMX via listeners added to the Javascript part of code. In this case I want to change DOM element(s) after an update on the page.

Below works fine:

document.body.addEventListener('htmx:afterSwap', (() => {
    // get input element, clear its value
}))

I'm using Alpine.js which helps handling dynamic parts on the client side. I want to connect it to HTMX events since it apparently picks up custom events.

Unfortunately, when trying to subscribe to any HTMX event, e.g. htmx:after-swap in

<form x-on:htmx:after-swap="console.log('event received')"
    hx-post="{% url 'my_url' %}"
    hx-target="#responses"
>

I have no output in the console.

Do I need to first trigger Alpine's 'custom event' from plain Javascript (e.g. in the working addEventListener block above) or can I connect HTMX with Alpine.js directly?

I have tried:

  • various cases combinations (I gather kebab is the way for Alpine.js);
  • tried various HTMX events such as htmx:load;
  • replaced x-on with @;
  • found HTMX+Alpine.js examples elsewhere (for instance involving x-data prefix) but none of them worked for me.

I would like to understand the process, thank you.


Solution

  • Alpine will not be able to listen to the event unless it's dispatched directly to the element where you added the listener, or a child element. In this particular case, adding the window modifier will most likely work.

    <form x-on:htmx:after-swap.window="console.log('event received')"
        hx-post="{% url 'my_url' %}"
        hx-target="#responses"
    >