| 1 | --- |
| 2 | title: "hx-on" |
| 3 | description: "Runs inline JavaScript when an event fires" |
| 4 | --- |
| 5 | |
| 6 | The `hx-on` attribute wires inline JavaScript to run when an event fires. |
| 7 | |
| 8 | It is an enhanced version of [`onevent` properties](https://developer.mozilla.org/en-US/docs/Web/Events/Event_handlers#using_onevent_properties) that keeps behavior in the markup ([Locality of Behaviour](/essays/locality-of-behaviour)). |
| 9 | |
| 10 | ## Syntax |
| 11 | |
| 12 | **Simple form** |
| 13 | |
| 14 | One event, one expression: |
| 15 | |
| 16 | ```html |
| 17 | <!-- hx-on:<event>=<js> --> |
| 18 | |
| 19 | <dialog hx-on:load="this.showModal()"> |
| 20 | ``` |
| 21 | |
| 22 | For htmx events, use `::` as shorthand for `htmx:`: |
| 23 | |
| 24 | ```html |
| 25 | <!-- hx-on::before:request is shorthand for hx-on:htmx:before:request --> |
| 26 | <button hx-get="/api" hx-on::before:request="showSpinner()"> |
| 27 | <button hx-get="/api" hx-on::after:request="hideSpinner()"> |
| 28 | ``` |
| 29 | |
| 30 | **Extended form** |
| 31 | |
| 32 | Builds on [`hx-trigger`](/reference/attributes/hx-trigger)'s grammar, adding `->` to wire events to JavaScript: |
| 33 | |
| 34 | ```html |
| 35 | <!-- hx-on="<event>[<filter>] <modifiers> [, ...] -> <js> | { <js>; ... } [; ...]" --> |
| 36 | |
| 37 | <!-- Open dialog on page load / swap --> |
| 38 | <dialog hx-on="load -> this.showModal()"> |
| 39 | |
| 40 | <!-- Unfocus input on Escape --> |
| 41 | <input hx-on="keydown[key=='Escape'] -> this.blur()"> |
| 42 | |
| 43 | <!-- Close dialog on custom event (e.g. HX-Trigger: closeDialog) --> |
| 44 | <dialog hx-on="closeDialog from:body -> this.close()"> |
| 45 | |
| 46 | <!-- Close on backdrop click OR custom event --> |
| 47 | <dialog hx-on="click from:self, closeDialog from:body -> this.close()"> |
| 48 | |
| 49 | <!-- Run multiple statements --> |
| 50 | <dialog hx-on="close -> this.remove(); log('dialog removed')"> |
| 51 | |
| 52 | <!-- Different code for different events --> |
| 53 | <dialog hx-on="load -> this.showModal(); |
| 54 | click from:self, closeDialog from:body -> this.close(); |
| 55 | close -> this.remove(); log('removed')"> |
| 56 | ``` |
| 57 | |
| 58 | - `->` event(s) on the left, JavaScript code on the right |
| 59 | - `,` multiple events, same code |
| 60 | - `;` separate event -> code pairs (only splits on the `;` immediately before a `->`, so semicolons in your JS are safe) |
| 61 | |
| 62 | ## Standard Events |
| 63 | |
| 64 | `hx-on` works with any DOM event: `click`, `input`, `keyup`, `submit`, etc. |
| 65 | |
| 66 | ```html |
| 67 | <button hx-on:click="..."> |
| 68 | <input hx-on:input="..."> |
| 69 | <form hx-on:submit="..."> |
| 70 | <div hx-on:mouseenter="..."> |
| 71 | ``` |
| 72 | |
| 73 | ## Custom Events |
| 74 | |
| 75 | Custom events work too. Dispatch them from JavaScript with [`htmx.trigger()`](/reference/methods/htmx-trigger), or from the server via the [`HX-Trigger`](/reference/headers/HX-Trigger) response header. |
| 76 | |
| 77 | Events from `HX-Trigger` are dispatched on the `body`, so use [`from:body`](#from) to listen for them: |
| 78 | |
| 79 | ```html |
| 80 | <div hx-on="productsUpdated from:body -> log('Products updated!')"> |
| 81 | ``` |
| 82 | |
| 83 | ## Synthetic Events |
| 84 | |
| 85 | htmx provides synthetic events beyond standard DOM events. |
| 86 | |
| 87 | These work with both the simple form (`hx-on:load`) and the extended form (`hx-on="load -> ..."`). |
| 88 | |
| 89 | ### `load` |
| 90 | |
| 91 | Fires when the element is loaded into the DOM. |
| 92 | |
| 93 | ```html |
| 94 | <div hx-on:load="this.classList.add('loaded')"> |
| 95 | ``` |
| 96 | |
| 97 | ### `revealed` |
| 98 | |
| 99 | Fires when the element is scrolled into the viewport. |
| 100 | |
| 101 | ```html |
| 102 | <div hx-on:revealed="this.classList.add('visible')"> |
| 103 | ``` |
| 104 | |
| 105 | _Note: `revealed` always observes the browser viewport. For scrollable containers with `overflow`, use [`intersect`](#intersect) with `root` instead._ |
| 106 | |
| 107 | ### `intersect` |
| 108 | |
| 109 | Fires when an element becomes visible in the viewport. |
| 110 | |
| 111 | Uses the [IntersectionObserver API](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver#options) and supports [`root`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/root), [`rootMargin`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/rootMargin), and [`threshold`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/thresholds) as modifiers. |
| 112 | |
| 113 | ```html |
| 114 | <div hx-on="intersect once -> this.classList.add('in-view')"> |
| 115 | <div hx-on="intersect rootMargin:100px -> this.classList.add('near')"> |
| 116 | ``` |
| 117 | |
| 118 | ### `every <time>` |
| 119 | |
| 120 | Fires repeatedly on an interval. Only available in the extended form. |
| 121 | |
| 122 | ```html |
| 123 | <div hx-on="every 1s -> this.textContent = new Date().toLocaleTimeString()"> |
| 124 | ``` |
| 125 | |
| 126 | ## Event Modifiers |
| 127 | |
| 128 | ### `[filter]` |
| 129 | |
| 130 | A JavaScript expression in brackets after the event name. Only fires when it evaluates to `true`. |
| 131 | |
| 132 | ```html |
| 133 | <button hx-on="click[ctrlKey] -> navigator.clipboard.writeText(this.textContent)"> |
| 134 | ``` |
| 135 | |
| 136 | Inside the brackets, all properties of the event are available as bare names: |
| 137 | |
| 138 | - [`click`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent#instance_properties) → `altKey`, `ctrlKey`, `shiftKey`, `metaKey`, ... |
| 139 | - [`keydown`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#instance_properties) → `key`, `code`, `repeat`, ... |
| 140 | |
| 141 | Global functions work too: `click[hasUnsavedChanges()]`. |
| 142 | |
| 143 | ### `once` |
| 144 | |
| 145 | Fires once, then stops listening. |
| 146 | |
| 147 | ```html |
| 148 | <button hx-on="click once -> this.textContent = 'Done!'">Click me</button> |
| 149 | ``` |
| 150 | |
| 151 | ### `changed` |
| 152 | |
| 153 | Only fires if the element's `value` changed since last time. |
| 154 | |
| 155 | ```html |
| 156 | <input hx-on="input changed -> console.log(this.value)"> |
| 157 | ``` |
| 158 | |
| 159 | Note: [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) is a DOM event. `changed` is an htmx modifier. Different things. |
| 160 | |
| 161 | ### `delay:<time>` |
| 162 | |
| 163 | Waits before firing. If the event fires again, the delay resets (debounce). |
| 164 | |
| 165 | ```html |
| 166 | <input hx-on="input delay:500ms -> console.log(this.value)"> |
| 167 | ``` |
| 168 | |
| 169 | ### `throttle:<time>` |
| 170 | |
| 171 | Fires, then ignores further events for the given interval. |
| 172 | |
| 173 | ```html |
| 174 | <div hx-on="scroll throttle:100ms -> this.dataset.scrollY = window.scrollY"></div> |
| 175 | ``` |
| 176 | |
| 177 | ### `from:<selector>` |
| 178 | |
| 179 | Listens on a different element. Takes a CSS selector or an [extended selector](/docs#extended-selectors-1). Two special values: `self` (only the element itself, not children) and `outside` (anything outside the element). |
| 180 | |
| 181 | ```html |
| 182 | <div hx-on="keydown[key=='Escape'] from:body -> this.hidden = true"> |
| 183 | <div hx-on="click from:outside -> this.hidden = true"> |
| 184 | ``` |
| 185 | |
| 186 | ### `target:<selector>` |
| 187 | |
| 188 | Only fires if `event.target` matches the given CSS selector. |
| 189 | |
| 190 | ```html |
| 191 | <ul hx-on="click target:li -> event.target.classList.toggle('selected')"></ul> |
| 192 | ``` |
| 193 | |
| 194 | ### `prevent` |
| 195 | |
| 196 | Calls `event.preventDefault()`. |
| 197 | |
| 198 | ```html |
| 199 | <form hx-on="submit prevent -> console.log(new FormData(this))"></form> |
| 200 | ``` |
| 201 | |
| 202 | ### `stop` / `consume` |
| 203 | |
| 204 | Calls `event.stopPropagation()`. |
| 205 | |
| 206 | ```html |
| 207 | <button hx-on="click stop -> this.textContent = 'clicked'"></button> |
| 208 | ``` |
| 209 | |
| 210 | ### `halt` |
| 211 | |
| 212 | Shorthand for `prevent stop`. |
| 213 | |
| 214 | ```html |
| 215 | <a hx-on="click halt -> console.log(this.href)"></a> |
| 216 | ``` |
| 217 | |
| 218 | ### `capture` |
| 219 | |
| 220 | Listens during the capture phase (top-down) instead of the bubble phase (bottom-up). |
| 221 | |
| 222 | ```html |
| 223 | <div hx-on="click capture -> console.log('capture:', event.target.tagName)"></div> |
| 224 | ``` |
| 225 | |
| 226 | ### `passive` |
| 227 | |
| 228 | Tells the browser the handler won't call `preventDefault()`, so the browser can scroll without waiting for your code to finish. |
| 229 | |
| 230 | ```html |
| 231 | <div hx-on="scroll passive -> this.dataset.scrollY = window.scrollY"></div> |
| 232 | ``` |
| 233 | |
| 234 | ## Symbols |
| 235 | |
| 236 | Like `onevent`, two symbols are made available to event handler scripts: |
| 237 | |
| 238 | ### `this` |
| 239 | |
| 240 | The element the `hx-on` attribute is on. |
| 241 | |
| 242 | ```html |
| 243 | <button hx-on:click="this.classList.toggle('active')">Toggle</button> |
| 244 | ``` |
| 245 | |
| 246 | ### `event` |
| 247 | |
| 248 | The event that fired. |
| 249 | |
| 250 | Any properties on `event.detail` are unpacked into scope, so you can write `message` instead of `event.detail.message`: |
| 251 | |
| 252 | ```html |
| 253 | <!-- dispatched with detail: { message: 'hello' } --> |
| 254 | <div hx-on="my-event -> alert(message)"> |
| 255 | <!-- equivalent to: alert(event.detail.message) --> |
| 256 | </div> |
| 257 | ``` |
| 258 | |
| 259 | ## Notes |
| 260 | |
| 261 | * Works with any event, including [htmx events](/reference#events). |
| 262 | * `hx-on` is _not_ inherited, but events on children still [bubble up](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture) and trigger it. |
| 263 | * Both forms (`hx-on:event` and `hx-on="..."`) can coexist on the same element. |
| 264 | * Browsers lowercase attribute names, so `hx-on:myEvent` won't match a `myEvent` dispatch. Use the extended form: `hx-on="myEvent -> ..."`. |
| 265 | ## See Also |
| 266 | |
| 267 | - [`hx-trigger`](/reference/attributes/hx-trigger) (attribute) |
| 268 | - [Client Scripting](/docs#client-side-scripting) (guide) |
| 269 | - [Extended Selectors](/docs#extended-selectors-1) (reference) |
| 270 | - [Locality of Behaviour](/essays/locality-of-behaviour) (essay) |