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:
- Why isn't "open dialog" logged to the console when I use the
HX-Trigger-After-Swap
header, but it works when I useHX-Trigger-After-Settle
? - How can I open the shoelace dialog after htmx has "loaded" the fragment without using
setTimeout
?