I’m trying to use htmx triggers and custom events without success. I’m using custom events because I’m going to trigger multiple refresh in a page. My source is very simple, but I cannot make it work:
<html>
<script src="./js/htmx.min.js"></script>
<body>
<div id="detailDiv" hx-trigger="startProcessing" hx-get="/api/messages.php">GO</div>
<script>
document.addEventListener("startProcessing", () => {
console.log("The startProcessing event was triggered")
});
htmx.trigger('#detailDiv','startProcessing')
</script>
</body>
</html>
HTMX is never triggered, and messages.php never called, while the javascript eventListener is correctly triggered. I do not understand why. Can you please post a full example of htmx reacting to javascript custom event?
I’ve lost so much time trying to figure out what the problem was.
2
Answers
Welcome to SO.
Your code works, but I guess HTMX has not processed
#detailDiv
yet when the event is triggered (immediately when the<script>
tag loads). Try waiting for the page to be fully loaded before triggering the event, as in this fiddle: https://jsfiddle.net/nyh8dtaj/ (see in the console how the request is sent upon running the fiddle)Ensure both DOM and HTMX are fully loaded, like: