最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTMX afterSwap and afterRequest events not raised on swapped content - Stack Overflow

programmeradmin3浏览0评论

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
  • Could you just include a script tag in the returned html or do you need the event details? If you want to reference the button you could use document.currentScript.previousElementSibling. – scrhartley Commented Feb 18 at 21:07
Add a comment  | 

2 Answers 2

Reset to default 1

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.

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')}"
发布评论

评论列表(0)

  1. 暂无评论