djangohtmx

How to execute javascript code after htmx makes an ajax request?


I'm currently building a website with django and htmx and i like the combination so far. Let's say I use an htmx attribute on a button to replace a div in the DOM with another div that is supposed to contain a wysiwyg editor. Now the wysiwyg editor has to be initialized with JavaScript. How do I do this? Can I just return the script tag under the editor div that is being requested with htmx? Wouldn't that be also a little ugly or bad practice because you'd have script tags in the middle of the html body? What's the best way of solving this?


Solution

  • Check out HTMX after request event.

    It should look something like this

    htmx.on('htmx:afterRequest', (evt) => {
      // check which element triggered the htmx request. If it's the one you want call the function you need
    //you have to add htmx: before the event ex: 'htmx:afterRequest'
    })