javascripthtmlhtmx

HTMX afterSwap and afterRequest events not raised on swapped content


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?


Solution

  • That 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.