A list of items with a "load more" button; the response will contain more items and a new button:
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<!-- ... -->
<div id="more">
<button hx-get="/load-items?page=2"
hx-on:htmx:after-swap="alert('swapped!')"
hx-target="#more"
hx-swap="outerHTML"
>Load more<button>
</div>
The afterSwap
and afterRequest
events are not raised / handled. I assume that's because it removes the original content?
How can I raise and handle the event despite the swap?
A list of items with a "load more" button; the response will contain more items and a new button:
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<!-- ... -->
<div id="more">
<button hx-get="/load-items?page=2"
hx-on:htmx:after-swap="alert('swapped!')"
hx-target="#more"
hx-swap="outerHTML"
>Load more<button>
</div>
The afterSwap
and afterRequest
events are not raised / handled. I assume that's because it removes the original content?
How can I raise and handle the event despite the swap?
Share Improve this question asked Feb 16 at 13:25 lonixlonix 20.9k29 gold badges132 silver badges274 bronze badges 1 |2 Answers
Reset to default 1That isn't possible as the button is swapped (i.e. removed) before the handler can run.
Option 1: based on info from the repo, one can use the beforeCleanupElement event:
hx-on:htmx:before-cleanup-element="console.log('hello')"
Option 2: One can use a regular event handler instead:
document.addEventListener('htmx:afterSwap', ev => {
let elSwapped = ev.detail.elt;
// use elSwapped...
console.log('hello');
};
Option 3: One can use hx-preserve.
Since the event is bubbled, You can move the hx-on
to parent element (outside of the swapped content).
The small downside in your case is that you additionally need to limit the logic to catch the latest event (since swap event will be fired multiple times - once for each parent element coming from the response)
e.g.
hx-on:htmx:after-swap="if(event.target.id == 'more') {console.log('hello')}"
document.currentScript.previousElementSibling
. – scrhartley Commented Feb 18 at 21:07