Johan
Johan

Reputation: 40588

HTMX doesn't seem to trigger event specified by HX-Trigger-After-Swap header

I have a thymeleaf fragment returned by the server from an HTMX request (using HTMX 1.9.0), that also includes a javascript function like this:

<script type="text/javascript">
    document.body.addEventListener("my-event", function() {
        console.log("open dialog");
        document.querySelector('.my-dialog').show();
    });
</script>

The response also includes a HX-Trigger-After-Swap header set to my-event. What I want to do is to log "open dialog" to the console and then call show() on a shoelace dialog that is also defined the in the fragment:

<sl-dialog label="Dialog" class="dialog-overview my-dialog">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  <sl-button slot="footer" variant="primary">Close</sl-button>
</sl-dialog>

But the dialog is not opened, and nothing is logged to the console, when the html is returned from the server. It's just like the event is never dispatched by htmx. If I instead return this javascript function:

<script type="text/javascript">
    setTimeout(function() {
        console.log("open dialog");
        document.querySelector('.my-dialog').show();
    }, 200);
</script>

then it works.

If I change the header to HX-Trigger-After-Settle instead of HX-Trigger-After-Swap, then "open dialog" is logged to the console, but the shoelace dialog is not opened because:

caught TypeError: document.querySelector(...).show is not a function
    at HTMLBodyElement.<anonymous> (<anonymous>:5:60)
    at ie (htmx.min.js:1:23945)
    at Me (htmx.min.js:1:12341)
    at o (htmx.min.js:1:40194)

Questions:

  1. Why isn't "open dialog" logged to the console when I use the HX-Trigger-After-Swap header, but it works when I use HX-Trigger-After-Settle?
  2. How can I open the shoelace dialog after htmx has "loaded" the fragment without using setTimeout?

Upvotes: 2

Views: 2480

Answers (1)

Jess
Jess

Reputation: 25137

This is a sad answer, but HT-Trigger response header is not supported on initial page load.

This is because the headers are processed immediately by the browser (not HTMX) and the element with hx-trigger is not in the DOM yet anyway.

https://github.com/bigskysoftware/htmx/issues/922

Upvotes: 0

Related Questions