Search code examples
javascripthtmlevent-handlinghtmx

HTMX: Passing a function to `hx-on` for reading the event


I must be missing the absolute obvious here:

Using htmx I am trying to send a get request and configure it in javascript before sending it. HTMX provides hx-get, hx-on and the configRequest event for basically exactly that.

However I seem to be missing a big obvious button since I could not get hx-on to perform a function or lambda I give it, only immediate JS works which (by it's nature) cannot accept arguments and therefor cannot access the event.

In short: What am I missing to get the following to work as expected?

<button hx-get="/api/things"
        hx-on:config-request="event => console.log('🙌 ', event)"
        hx-target="#target"
>Click Me!</button>
<p id="target">...</p>
  • hx-on:config-request="console.log('This will work 👍')" will work but obviously cannot engage with the event.
  • hx-on:config-request="() => console.log('This won't work 👎')" won't work
  • hx-on:config-request="console.log" won't work as well
  • hx-on:config-request="someOtherKnownMethod" won't work as well

I'm confused. 😕

Thanks for your time. Some ideas?


Solution

  • The event keyword is accessible directly, so you don't need to use lambda function. Also you're missing "::" which is a shorter way of accessing htmx events.

    Smth like this should work (make sure you have the latest htmx js lib version):

    hx-on::config-request="console.log('🙌 ', event)"