Nathaniel Sabanski 360331d25a
hx-on: Added to Reference page, and revised docs: readability, wordiness. (#1365)
* hx-on: Added to Reference page, and revised docs, removed words.

* hx-on: Made first sample a <div> to showcase versatility.

* Minor revision.

* Minor revision.

* Fixed broken Locality of Behavior link.
2023-04-13 12:17:13 -06:00

1.5 KiB

+++ title = "hx-on" +++

The hx-on attribute allows you to embed scripts inline to respond to events directly on an element; similar to the onevent properties found in HTML, such as onClick.

hx-on improves upon onevent by enabling the handling of any event for enhanced Locality of Behaviour (LoB). This also enables you to handle any htmx event.

The value is an event name, followed by a colon :, followed by the script:

<div hx-on="click: alert('Clicked!')">Click</div>

All htmx events can be captured, too!

<button hx-get="/info" hx-on="htmx:beforeRequest: alert('Making a request!')">
    Get Info!
</button>

Symbols

Like onevent, two symbols are made available to event handler scripts:

  • this - The element on which the hx-on attribute is defined
  • event - The event that triggered the handler

Multiple Handlers

Multiple handlers can be defined by putting them on new lines:

<button hx-get="/info" hx-on="htmx:beforeRequest: alert('Making a request!')
                              htmx:afterRequest: alert('Done making a request!')">
    Get Info!
</button>

Notes

  • hx-on is not inherited, however due to event bubbling, hx-on attributes on parent elements will typically be triggered by events on child elements