'Trigger polling using htmx.trigger

I'm trying to trigger a polling behavior on a div using JavaScript.

This is the div.

<div id="myId" hx-get="https://xxxx" hx-swap="innerHTML"></div>

This is the trigger function.

 htmx.trigger(
   htmx.find(`#myId`),
   "every 300ms"
 );

But it's not working. Is there a way to obtain this behavior?



Solution 1:[1]

You can have your JavaScript set up the polling interval. Then you can trigger a custom event and have your div listen for it.

To have the server stop the client polling, put a different custom event in the Response Headers and listen for it on the client. Included is how you would add the response header if your server was ASP.NET, since I'm not sure what you are running server-side. Also innerHTML is the default hx-swap target, so could be omitted.

HTMX:

<div id="myId" hx-get="https://xxxx" hx-trigger="myEvent"></div>

JS:

// start polling
function startpolling(){
var myPoller= setInterval(function () {  htmx.trigger("myId","myEvent"); }, 300);
}

// stop polling
document.body.addEventListener("stopPolling", function(evt){
    clearInterval(myPoller);
})

ASP.NET Server code:

HttpContext.Response.Headers.Add("HX-Trigger", "stopPolling");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeremy Caney