skip to Main Content

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


  1. 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)

    document.addEventListener('DOMContentLoaded', () => {
        htmx.trigger('#detailDiv', 'startProcessing');
    });
    
    Login or Signup to reply.
  2. Ensure both DOM and HTMX are fully loaded, like:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
    
    <div id="detailDiv" hx-trigger="startProcessing" hx-get="/api/messages.php">GO</div>
    
    <script>
        document.addEventListener('DOMContentLoaded', (event) => {
            document.addEventListener("startProcessing", () => {
                console.log("The startProcessing event was triggered");
            });
    
            htmx.onLoad(function() {
                htmx.trigger('#detailDiv', 'startProcessing');
            });
        });
    </script>
    
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search