Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I trigger an element-based HTMX GET request from vanilla JavaScript?

Using HTMX, I have an element rigged up with hx-get and hx-trigger, and it works fine. But under certain circumstances, I want the GET request to trigger from some vanilla JavaScript logic (which is not based on user input).

I've looked through the JavaScript API, and I'm just not seeing it. There's an htmx.trigger(), but it seems to just trigger the standard HTML events, not an element-based event.

I can do this all manually in JavaScript, of course, but I feel like there has to be a way to get HTMX to do it.

like image 591
Deane Avatar asked Oct 27 '25 02:10

Deane


1 Answers

I got it.

You can do this in the hx-trigger element:

<input hx-trigger="[all your other triggers], doSearch from:body" ...

The trigger will now work in the all the other ways defined, and it will also listen for an event called doSearch from the BODY element..

You raise that event like this:

// Do a bunch of logic here, then...
document.body.dispatchEvent(new Event('doSearch'));
like image 148
Deane Avatar answered Oct 29 '25 18:10

Deane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!