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:
htmx:load
;x-on
with @
;x-data
prefix) but none of them worked for me.I would like to understand the process, thank you.
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"
>