javascriptaddeventlistenerhtmx

HTMX hx:afterRequest event not calling


I need to call call some JS after having called an HTMX request, like this:

document.addEventListener('htmx:afterRequest', updateConnections())

In updateConnections() I need to reassign some references to html elements that may have been changed during the swap. It is running once on the initial reload of the page and then does nothing when HTMX requests are called in the page using hx-post and hx-get. What could be the problem?

The JS is for sure still running even after the HTMX requests, since other parts of the functionality still remains.

**EDIT: ** Here is the code now, and it still does not work:

$(document).ready(() => {
    var hxCounter = 1

    function updateConnections() {
        console.log(`Reasigning the js references(${hxCounter})`)
        hxCounter += 1
    }
    document.body.addEventListener('htmx:afterRequest', updateConnections())
}

If it makes any difference I am using Django with HTMX and the JS is in a static file that is loaded into the base of the HTML, and should never change across the hx-requests.


Solution

  • Listen to the event on the body instead.

    document.body.addEventListener('htmx:afterRequest', updateConnections())
    
    

    Just be aware that because all events bubble to the body, any HTMX request will trigger updateConnections(). I hope that's what you need, otherwise you will need to listen to the event on the actual element making that particular HTMX request.

    EDIT

    The code works. You think it's not working because you are logging what should be the updated hxCounter. The problem in your code is that every time you make an HTMX request, hxCounter will be reset to 1 because you're redeclaring it. To demonstrate it, use the let keyword to define the hxCounter and you will see SyntaxError: redeclaration of let hxCounter error. The var keyword does not throw this error because it lets you do this.

    To confirm that the event listener on the body is working, define (with var) hxCounter as an object rather than an integer.

    var hxCounter = {count: 0}
    
    // Then your function
    function updateConnections() {
    hxCounter.count += 1
    console.log(hxCounter.count)
    }
    
    document.body.addEventListener("htmx:afterRequest", ()=> {updateConnections()})