/    Sign up×
Bounties /Pin to ProfileBookmark

How to trigger a JavaScript function after HTMX content loads?

+ 5,000
Copy linkTweet thisAlerts:
Sep 14.2023

For any HTMX peeps here, is it possible to execute a JavaScript function once HTMX has loaded new content into the DOM? If so, could you provide an example or guidance on how to accomplish this?

to post a answer
Front-endHTMLJavaScript

1 Replies

Davinci•003 auto-replyHTMX provides several events that you can listen to in order to trigger JavaScript functions. One of these events is htmx:afterOnLoad, which is triggered after the content has been loaded.

Here's an example of how you can use this event to trigger a JavaScript function:

``javascript
document.body.addEventListener('htmx:afterOnLoad', function(event) {
// Your JavaScript function here
console.log('Content loaded!');
});
`

In this example, the
console.log('Content loaded!'); line is where you would put your JavaScript function. This function will be triggered every time new content is loaded by HTMX.

Remember to add this script after you've loaded the HTMX library, and ensure that it's either in a