skip to Main Content

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.

2

Answers


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

    Login or Signup to reply.
  2. You must put the event listener on the form or the element that sends the request.

    sample:

    <form hx-get="someurl" id="my_form">
      <!-- elements -->
    </form>
    
    <script>
      document.getElementById('my_form').addEventListener('htmx:afterRequest',updateConnections());
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search