javascripthtmlevent-handlinghtmx

Global event handlers for HTMX


I can define inline event handlers for various htmx events like so:

<button hx-on:htmx:after-request="..."
        hx-on:htmx:response-error="..."
        class="foo"
        >Load</button>        

But is it possible to define "global" event handlers?

For example, when a user loses his network connection, I'd like to show a toast with "Please retry in a few moments" rather than degrading his UX. I could add handlers inline (e.g. hx-on:htmx:after-sendError="...") but I don't want to do that for every HTMX-enabled element, I'd rather do that once, if possible.


Solution

  • HTMX also has "global" event handlers.

    So one can handle network problems associated with the htmx:sendError and htmx:timeout events like so:

    document.body.addEventListener('htmx:sendError', function(ev) {
      console.log(ev.detail);
      // ...show toast, etc.
    });
    
    document.body.addEventListener('htmx:timeout', function(ev) {
      console.log(ev.detail);
      // ...show toast, etc.
    });