| 1 | --- |
| 2 | name: htmx-guidance |
| 3 | description: Use when writing HTML with htmx, building htmx-powered pages, or answering questions about htmx patterns and best practices. Covers htmx 4 attributes, events, swap strategies, and common UI patterns. |
| 4 | --- |
| 5 | |
| 6 | # htmx 4 Guidance |
| 7 | |
| 8 | htmx allows any HTML element to issue HTTP requests and swap the response into the DOM. |
| 9 | The server returns **HTML fragments**, not JSON. This is the fundamental model. |
| 10 | |
| 11 | htmx 4 uses the `fetch()` API (not XMLHttpRequest like htmx 2). |
| 12 | |
| 13 | ## Core Attributes |
| 14 | |
| 15 | Issue requests with these attributes. Each takes a URL: |
| 16 | |
| 17 | | Attribute | Description | |
| 18 | |-------------|----------------| |
| 19 | | `hx-get` | GET request | |
| 20 | | `hx-post` | POST request | |
| 21 | | `hx-put` | PUT request | |
| 22 | | `hx-patch` | PATCH request | |
| 23 | | `hx-delete` | DELETE request | |
| 24 | |
| 25 | ### Default Triggers |
| 26 | |
| 27 | - `input`, `textarea`, `select` trigger on `change` |
| 28 | - `form` triggers on `submit` |
| 29 | - Everything else triggers on `click` |
| 30 | |
| 31 | Override with `hx-trigger`. |
| 32 | |
| 33 | ## hx-trigger |
| 34 | |
| 35 | Specify what event triggers the request: |
| 36 | |
| 37 | ```html |
| 38 | |
| 39 | <div hx-get="/data" hx-trigger="mouseenter">Hover me</div> |
| 40 | ``` |
| 41 | |
| 42 | **Modifiers:** |
| 43 | |
| 44 | - `once` -- fire only once |
| 45 | - `changed` -- only if value changed |
| 46 | - `delay:<time>` -- debounce (resets on re-trigger), e.g. `delay:500ms` |
| 47 | - `throttle:<time>` -- throttle (ignores during cooldown) |
| 48 | - `from:<selector>` -- listen on a different element (supports `document`, `window`, `closest <sel>`, `find <sel>`, |
| 49 | `next`, `previous`) |
| 50 | - `target:<selector>` -- filter by event target |
| 51 | - `consume` -- stop event from triggering other htmx requests on parents |
| 52 | |
| 53 | **Filters** (JavaScript expressions in brackets): |
| 54 | |
| 55 | ```html |
| 56 | |
| 57 | <div hx-get="/data" hx-trigger="click[ctrlKey]">Ctrl+Click me</div> |
| 58 | ``` |
| 59 | |
| 60 | **Special events:** |
| 61 | |
| 62 | - `load` -- fires when element is loaded |
| 63 | - `revealed` -- fires when element scrolls into viewport |
| 64 | - `intersect` -- fires on intersection (options: `root:<sel>`, `threshold:<float>`) |
| 65 | |
| 66 | **Polling:** |
| 67 | |
| 68 | ```html |
| 69 | |
| 70 | <div hx-get="/updates" hx-trigger="every 2s">Poll</div> |
| 71 | ``` |
| 72 | |
| 73 | **Multiple triggers** (comma-separated): |
| 74 | |
| 75 | ```html |
| 76 | <input hx-get="/search" hx-trigger="input changed delay:500ms, keyup[key=='Enter']" |
| 77 | hx-target="#results"> |
| 78 | ``` |
| 79 | |
| 80 | **Triggering from HX-Trigger header** -- use `from:body`: |
| 81 | |
| 82 | ```html |
| 83 | |
| 84 | <div hx-get="/table" hx-trigger="refreshTable from:body">...</div> |
| 85 | ``` |
| 86 | |
| 87 | ## hx-target |
| 88 | |
| 89 | CSS selector for where the response content goes. Defaults to the element itself. |
| 90 | |
| 91 | **Extended CSS selectors:** |
| 92 | |
| 93 | - `this` -- the element with the attribute |
| 94 | - `closest <selector>` -- nearest ancestor matching selector |
| 95 | - `find <selector>` -- first child descendant matching selector |
| 96 | - `next [selector]` -- next sibling (optionally matching selector) |
| 97 | - `previous [selector]` -- previous sibling (optionally matching selector) |
| 98 | |
| 99 | The relative selectors can be used to avoid adding ids to DOM elements, for example in a |
| 100 | table generated by a loop. |
| 101 | |
| 102 | ```html |
| 103 | |
| 104 | <button hx-get="/data" hx-target="closest .container">Load</button> |
| 105 | ``` |
| 106 | |
| 107 | ## hx-swap |
| 108 | |
| 109 | Controls how response content is placed relative to the target. Default: `innerHTML`. |
| 110 | |
| 111 | | Value | Description | |
| 112 | |--------------------------|----------------------------------------------------| |
| 113 | | `innerHTML` | Replace inner HTML of target | |
| 114 | | `outerHTML` | Replace entire target element | |
| 115 | | `innerMorph` | Morph children of target (preserves DOM state) | |
| 116 | | `outerMorph` | Morph target itself (preserves DOM state) | |
| 117 | | `textContent` | Replace text content, no HTML parsing | |
| 118 | | `before` / `beforebegin` | Insert before the target | |
| 119 | | `prepend` / `afterbegin` | Insert before target's first child | |
| 120 | | `append` / `beforeend` | Insert after target's last child | |
| 121 | | `after` / `afterend` | Insert after the target | |
| 122 | | `delete` | Delete the target regardless of response | |
| 123 | | `none` | Don't swap (OOB swaps and headers still processed) | |
| 124 | |
| 125 | **Modifiers** (space-separated after swap style): |
| 126 | |
| 127 | ```html |
| 128 | |
| 129 | <div hx-get="/data" hx-swap="innerHTML swap:100ms settle:200ms transition:true ignoreTitle:true scroll:top"> |
| 130 | ``` |
| 131 | |
| 132 | | Modifier | Description | |
| 133 | |---------------------|----------------------------------------------| |
| 134 | | `swap:<time>` | Delay before swap | |
| 135 | | `settle:<time>` | Delay between swap and settle | |
| 136 | | `transition:true` | Use View Transitions API | |
| 137 | | `ignoreTitle:true` | Don't update page title from response | |
| 138 | | `scroll:top/bottom` | Scroll target after swap | |
| 139 | | `show:top/bottom` | Scroll target into viewport | |
| 140 | | `strip:true` | Remove outer wrapper element before swapping | |
| 141 | | `focus-scroll:true` | Scroll to focused element | |
| 142 | | `target:<selector>` | Retarget the swap | |
| 143 | |
| 144 | ## Attribute Inheritance (CRITICAL htmx 4 change) |
| 145 | |
| 146 | **In htmx 4, inheritance is explicit by default.** Use the `:inherited` modifier on parent elements: |
| 147 | |
| 148 | ```html |
| 149 | <!-- WRONG in htmx 4: children won't inherit hx-target --> |
| 150 | <div hx-target="#output"> |
| 151 | <button hx-get="/a">A</button> |
| 152 | <button hx-get="/b">B</button> |
| 153 | </div> |
| 154 | |
| 155 | <!-- CORRECT: use :inherited modifier --> |
| 156 | <div hx-target:inherited="#output"> |
| 157 | <button hx-get="/a">A</button> |
| 158 | <button hx-get="/b">B</button> |
| 159 | </div> |
| 160 | ``` |
| 161 | |
| 162 | The `:append` modifier appends to inherited values: |
| 163 | |
| 164 | ```html |
| 165 | |
| 166 | <div hx-include:inherited="[name='token']"> |
| 167 | <button hx-post="/save" hx-include:inherited:append="[name='extra']">Save</button> |
| 168 | </div> |
| 169 | ``` |
| 170 | |
| 171 | To revert to implicit inheritance globally: set `htmx.config.implicitInheritance = true`. |
| 172 | |
| 173 | ## Configuration |
| 174 | |
| 175 | Set via meta tag or JavaScript: |
| 176 | |
| 177 | ```html |
| 178 | |
| 179 | <meta name="htmx-config" content='{"defaultSwap":"outerHTML"}'> |
| 180 | ``` |
| 181 | |
| 182 | Key config values: |
| 183 | |
| 184 | | Config | Default | Description | |
| 185 | |-----------------------|-------------------------|--------------------------------------------------------| |
| 186 | | `defaultSwap` | `innerHTML` | Default swap strategy | |
| 187 | | `defaultTimeout` | `60000` | Request timeout (ms) | |
| 188 | | `noSwap` | `[204, 304]` | Status codes that skip swapping | |
| 189 | | `implicitInheritance` | `false` | Auto-inherit attributes from parents | |
| 190 | | `transitions` | `false` | Enable View Transitions globally | |
| 191 | | `logAll` | `false` | Log all events to console (debugging) | |
| 192 | | `mode` | `same-origin` | Fetch mode (`cors`, `no-cors`, `same-origin`) | |
| 193 | | `history` | `true` | Enable history support (`true`, `false`, `"reload"`) | |
| 194 | | `extensions` | `""` | Whitelist of allowed extensions (empty = allow all) | |
| 195 | | `prefix` | `""` | Custom attribute prefix (e.g. `"data-hx-"`) | |
| 196 | | `morphIgnore` | `["data-htmx-powered"]` | Attribute name prefixes to leave unchanged when morphing | |
| 197 | | `morphScanLimit` | `10` | Sibling scan limit during morphing | |
| 198 | | `morphSkip` | `'[hx-morph-skip]'` | CSS selector for elements to skip morphing entirely | |
| 199 | | `morphSkipChildren` | `'[hx-morph-skip-children]'` | CSS selector for elements whose children skip morphing | |
| 200 | |
| 201 | ## Events |
| 202 | |
| 203 | htmx 4 naming convention: `htmx:phase:action` |
| 204 | |
| 205 | **Lifecycle:** |
| 206 | |
| 207 | - `htmx:before:init` / `htmx:after:init` -- element initialization |
| 208 | - `htmx:before:cleanup` / `htmx:after:cleanup` -- element removal |
| 209 | |
| 210 | **Request:** |
| 211 | |
| 212 | - `htmx:config:request` -- configure request (modify headers, body, URL). Cancel with `evt.preventDefault()` |
| 213 | - `htmx:before:request` -- just before fetch. Cancel with `evt.preventDefault()` |
| 214 | - `htmx:before:response` -- after fetch response received, before body consumed |
| 215 | - `htmx:after:request` -- after request completes |
| 216 | - `htmx:finally:request` -- always fires (like `finally` block) |
| 217 | - `htmx:error` -- on any error (network, response, swap) |
| 218 | |
| 219 | **Swap:** |
| 220 | |
| 221 | - `htmx:before:swap` / `htmx:after:swap` -- before/after content swap |
| 222 | - `htmx:before:settle` / `htmx:after:settle` -- before/after settle phase |
| 223 | - `htmx:confirm` -- after trigger, before request (for async confirmation) |
| 224 | |
| 225 | **History:** |
| 226 | |
| 227 | - `htmx:before:history:update` / `htmx:after:history:update` |
| 228 | - `htmx:after:history:push` / `htmx:after:history:replace` |
| 229 | - `htmx:before:history:restore` |
| 230 | |
| 231 | **View Transitions:** |
| 232 | |
| 233 | - `htmx:before:viewTransition` / `htmx:after:viewTransition` |
| 234 | |
| 235 | ### Request Context |
| 236 | |
| 237 | Events expose `detail.ctx` with the full request context: |
| 238 | |
| 239 | ```js |
| 240 | document.body.addEventListener('htmx:config:request', (evt) => { |
| 241 | let ctx = evt.detail.ctx; |
| 242 | // ctx.sourceElement -- element that triggered request |
| 243 | // ctx.target -- swap target element |
| 244 | // ctx.swap -- hx-swap value |
| 245 | // ctx.request.action -- URL |
| 246 | // ctx.request.method -- HTTP method |
| 247 | // ctx.request.headers -- headers object |
| 248 | // ctx.request.body -- FormData body |
| 249 | }); |
| 250 | ``` |
| 251 | |
| 252 | ### Inline Event Handlers |
| 253 | |
| 254 | Use `hx-on:event-name` for inline handlers: |
| 255 | |
| 256 | ```html |
| 257 | |
| 258 | <button hx-get="/data" hx-on:htmx:after:swap="alert('Swapped!')">Load</button> |
| 259 | ``` |
| 260 | |
| 261 | ## HTTP Headers |
| 262 | |
| 263 | ### Request Headers (sent by htmx) |
| 264 | |
| 265 | | Header | Description | |
| 266 | |------------------------------|---------------------------------------------------------------------------------| |
| 267 | | `HX-Request` | Always `"true"` for htmx requests | |
| 268 | | `HX-Source` | Triggering element as `tag#id` (e.g. `button#submit`) | |
| 269 | | `HX-Target` | Target element as `tag#id` (e.g. `div#results`) | |
| 270 | | `HX-Current-URL` | Browser's current URL | |
| 271 | | `HX-Request-Type` | `"partial"` for targeted swaps, `"full"` when targeting body or using hx-select | |
| 272 | | `HX-Boosted` | `"true"` if via hx-boost | |
| 273 | | `HX-History-Restore-Request` | `"true"` if restoring history | |
| 274 | |
| 275 | ### Response Headers (server sends to htmx) |
| 276 | |
| 277 | | Header | Description | |
| 278 | |------------------|--------------------------------------------------| |
| 279 | | `HX-Trigger` | Trigger client-side events (single name or JSON) | |
| 280 | | `HX-Push-Url` | Push URL to browser history | |
| 281 | | `HX-Replace-Url` | Replace current URL in history | |
| 282 | | `HX-Redirect` | Client-side redirect (full page) | |
| 283 | | `HX-Location` | Client-side redirect via AJAX (no full reload) | |
| 284 | | `HX-Refresh` | Full page refresh if `"true"` | |
| 285 | | `HX-Retarget` | Override target with CSS selector | |
| 286 | | `HX-Reswap` | Override swap strategy | |
| 287 | | `HX-Reselect` | Override hx-select | |
| 288 | |
| 289 | ## Status-Based Response Handling (hx-status) |
| 290 | |
| 291 | Handle different HTTP status codes with different swap behavior: |
| 292 | |
| 293 | ```html |
| 294 | |
| 295 | <form hx-post="/register" |
| 296 | hx-target="#result" |
| 297 | hx-status:422="target:#errors select:#validation-errors" |
| 298 | hx-status:5xx="swap:none"> |
| 299 | <input name="email" type="email"> |
| 300 | <div id="errors"></div> |
| 301 | <div id="result"></div> |
| 302 | <button type="submit">Register</button> |
| 303 | </form> |
| 304 | ``` |
| 305 | |
| 306 | Supports wildcards: `hx-status:5xx`, `hx-status:50x`, `hx-status:404`. |
| 307 | |
| 308 | Config options in the value: `swap:`, `target:`, `select:`, `push:`, `replace:`, `transition:`. |
| 309 | |
| 310 | ## Updating Multiple Page Regions |
| 311 | |
| 312 | Three main approaches: |
| 313 | |
| 314 | ### 1. Expand the Target |
| 315 | |
| 316 | Wrap both regions in a container and target it: |
| 317 | |
| 318 | ```html |
| 319 | |
| 320 | <div id="page-section"> |
| 321 | <div id="table">...</div> |
| 322 | <form hx-post="/contacts" hx-target="#page-section">...</form> |
| 323 | </div> |
| 324 | ``` |
| 325 | |
| 326 | Server returns both the table and the form. |
| 327 | |
| 328 | ### 2. Out-of-Band Swaps |
| 329 | |
| 330 | Server response includes extra elements with `hx-swap-oob`: |
| 331 | |
| 332 | ```html |
| 333 | <!-- Main response content (swapped into target normally) --> |
| 334 | <form>...</form> |
| 335 | |
| 336 | <!-- This gets swapped into #contacts-table by ID --> |
| 337 | <tbody hx-swap-oob="beforeend:#contacts-table"> |
| 338 | <tr> |
| 339 | <td>New row</td> |
| 340 | </tr> |
| 341 | </tbody> |
| 342 | ``` |
| 343 | |
| 344 | Note: in htmx 4, OOB swaps happen AFTER the main content swap. |
| 345 | |
| 346 | ### 3. Partial Tags |
| 347 | |
| 348 | New in htmx 4, a more general version of OOB swaps |
| 349 | |
| 350 | ```html |
| 351 | |
| 352 | <hx-partial hx-target="#messages" hx-swap="beforeend"> |
| 353 | <div>New message</div> |
| 354 | </hx-partial> |
| 355 | |
| 356 | <hx-partial hx-target="#notifications" hx-swap="innerHTML"> |
| 357 | <span class="badge">5</span> |
| 358 | </hx-partial> |
| 359 | ``` |
| 360 | |
| 361 | Each `<hx-partial>` specifies its own target and swap strategy. Preferred over OOB for explicit targeting. |
| 362 | |
| 363 | ### 4. Event-Driven Refresh |
| 364 | |
| 365 | Server sends `HX-Trigger: newContact` header. Table listens for the event: |
| 366 | |
| 367 | ```html |
| 368 | |
| 369 | <tbody id="contacts-table" |
| 370 | hx-get="/contacts/table" |
| 371 | hx-trigger="newContact from:body"> |
| 372 | ... |
| 373 | </tbody> |
| 374 | ``` |
| 375 | |
| 376 | ## Morphing |
| 377 | |
| 378 | `innerMorph` and `outerMorph` merge new content into the existing DOM instead of replacing it. |
| 379 | |
| 380 | **Preserves:** focus, scroll position, CSS animations, event listeners, playing video, form input values. |
| 381 | |
| 382 | **ID matching** is highest priority -- elements with matching IDs are updated in place. |
| 383 | |
| 384 | **Warning:** morphing preserves user input values. It cannot be used to reset forms -- use `innerHTML`/`outerHTML` for |
| 385 | that. |
| 386 | |
| 387 | **Excluding elements from morphing** — add attributes to your server templates: |
| 388 | |
| 389 | ```html |
| 390 | <!-- freeze entire element: attrs + children unchanged --> |
| 391 | <custom-widget hx-morph-skip>...</custom-widget> |
| 392 | |
| 393 | <!-- freeze only children: attrs still update --> |
| 394 | <lit-component hx-morph-skip-children>...</lit-component> |
| 395 | ``` |
| 396 | |
| 397 | Or set CSS selectors globally in config: |
| 398 | |
| 399 | ```javascript |
| 400 | htmx.config.morphSkip = 'custom-widget, .frozen'; |
| 401 | htmx.config.morphSkipChildren = 'lit-component, .sortable'; |
| 402 | ``` |
| 403 | |
| 404 | ## Other Attributes |
| 405 | |
| 406 | | Attribute | Description | |
| 407 | |------------------|---------------------------------------------------------------------------| |
| 408 | | `hx-select` | CSS selector to pick part of the response | |
| 409 | | `hx-select-oob` | Pick out elements by ID for OOB swap | |
| 410 | | `hx-include` | Include additional elements' values in request | |
| 411 | | `hx-vals` | Add values to request. Supports `js:` prefix for dynamic values | |
| 412 | | `hx-headers` | Add custom headers to request | |
| 413 | | `hx-indicator` | Element to show during request (gets `htmx-request` class) | |
| 414 | | `hx-confirm` | Show confirmation dialog. Supports `js:` prefix for async confirmation | |
| 415 | | `hx-sync` | Synchronize requests between elements | |
| 416 | | `hx-boost` | Progressive enhancement for links and forms | |
| 417 | | `hx-config` | Per-element fetch config as JSON (`timeout`, `credentials`, `mode`, etc.) | |
| 418 | | `hx-preserve` | Keep element unchanged across swaps | |
| 419 | | `hx-ignore` | Disable htmx processing for element and children | |
| 420 | | `hx-disable` | Disable specified elements during requests | |
| 421 | | `hx-preload` | Preload content on trigger events | |
| 422 | | `hx-optimistic` | Show optimistic content during request | |
| 423 | | `hx-push-url` | Push URL to browser history | |
| 424 | | `hx-replace-url` | Replace URL in browser history | |
| 425 | | `hx-encoding` | Change encoding (e.g. `multipart/form-data` for file uploads) | |
| 426 | | `hx-validate` | Validate form elements before request | |
| 427 | |
| 428 | ## Parameters |
| 429 | |
| 430 | - Non-GET/DELETE requests automatically include enclosing form values |
| 431 | - GET and DELETE do NOT include enclosing form data. Use `hx-include="closest form"` if needed |
| 432 | - Use `hx-vals='{"key": "value"}'` for static values |
| 433 | - Use `hx-vals='js:{"key": computeValue()}'` for dynamic values |
| 434 | |
| 435 | ## JavaScript API |
| 436 | |
| 437 | ```js |
| 438 | htmx.ajax("GET", "/data", {target: "#result"}) // Programmatic request, returns Promise |
| 439 | htmx.on("htmx:after:swap", (evt) => { ... |
| 440 | }) // Event listener |
| 441 | htmx.onLoad((elt) => { ... |
| 442 | }) // Process new content |
| 443 | htmx.process(element) // Initialize htmx on dynamic content |
| 444 | htmx.find("closest .container") // Extended CSS selector query |
| 445 | htmx.findAll(".items") // Find all matching |
| 446 | htmx.trigger(elt, "myEvent", {detail: ...}) // Fire custom event |
| 447 | htmx.swap(ctx) // Manual swap |
| 448 | htmx.timeout(1000) // Promise that resolves after delay |
| 449 | htmx.live.take(elt, "active", ".tab") // Take class — provided by hx-live |
| 450 | htmx.live.forEvent(elt, "click", 5000) // Race events/timeouts — provided by hx-live |
| 451 | htmx.live.nextFrame() // requestAnimationFrame promise — provided by hx-live |
| 452 | ``` |
| 453 | |
| 454 | ## Common Patterns |
| 455 | |
| 456 | ### Active Search |
| 457 | |
| 458 | ```html |
| 459 | <input type="text" name="q" |
| 460 | hx-get="/search" |
| 461 | hx-trigger="input changed delay:500ms, keyup[key=='Enter']" |
| 462 | hx-target="#search-results" |
| 463 | hx-indicator="#spinner"> |
| 464 | <span id="spinner" class="htmx-indicator">Searching...</span> |
| 465 | <div id="search-results"></div> |
| 466 | ``` |
| 467 | |
| 468 | ### Lazy Loading |
| 469 | |
| 470 | ```html |
| 471 | |
| 472 | <div hx-get="/lazy-content" hx-trigger="load" hx-swap="outerHTML"> |
| 473 | Loading... |
| 474 | </div> |
| 475 | ``` |
| 476 | |
| 477 | ### Infinite Scroll |
| 478 | |
| 479 | ```html |
| 480 | |
| 481 | <tr hx-get="/page/3" hx-trigger="revealed" hx-swap="afterend"> |
| 482 | <!-- last row of current page --> |
| 483 | </tr> |
| 484 | ``` |
| 485 | |
| 486 | ### Click to Load More |
| 487 | |
| 488 | ```html |
| 489 | |
| 490 | <button hx-get="/page/2" hx-target="#results" hx-swap="beforeend"> |
| 491 | Load More |
| 492 | </button> |
| 493 | ``` |
| 494 | |
| 495 | ### Edit in Place |
| 496 | |
| 497 | ```html |
| 498 | |
| 499 | <div hx-get="/contact/1/edit" hx-trigger="click" hx-swap="outerHTML"> |
| 500 | <p>Click to edit</p> |
| 501 | </div> |
| 502 | ``` |
| 503 | |
| 504 | Server returns an edit form. Form submits via hx-post and returns the display view. |
| 505 | |
| 506 | ### Tabs |
| 507 | |
| 508 | ```html |
| 509 | |
| 510 | <div role="tablist" hx-target:inherited="#tab-content"> |
| 511 | <button role="tab" hx-get="/tab/1" class="active">Tab 1</button> |
| 512 | <button role="tab" hx-get="/tab/2">Tab 2</button> |
| 513 | </div> |
| 514 | <div id="tab-content">...</div> |
| 515 | ``` |
| 516 | |
| 517 | ### Form Validation |
| 518 | |
| 519 | ```html |
| 520 | |
| 521 | <form hx-post="/register" |
| 522 | hx-target="#result" |
| 523 | hx-status:422="target:#errors"> |
| 524 | <input name="email" type="email"> |
| 525 | <div id="errors"></div> |
| 526 | <div id="result"></div> |
| 527 | <button type="submit">Register</button> |
| 528 | </form> |
| 529 | ``` |
| 530 | |
| 531 | Server returns 422 with error HTML, target becomes the element with the errors id, or 200 with success HTML target is |
| 532 | the element with the id `result`. |
| 533 | |
| 534 | ### Loading Indicators |
| 535 | |
| 536 | ```html |
| 537 | |
| 538 | <button hx-get="/slow" hx-indicator="#loading"> |
| 539 | Load |
| 540 | <img id="loading" class="htmx-indicator" src="/spinner.gif" alt="Loading..."> |
| 541 | </button> |
| 542 | ``` |
| 543 | |
| 544 | The `htmx-indicator` class hides the element by default (opacity: 0). When a request is in flight, `htmx-request` class |
| 545 | is added, making indicators visible. |
| 546 | |
| 547 | To avoid flashing the spinner on fast requests, add a `transition-delay` (the second time value) to the indicator's CSS: |
| 548 | |
| 549 | ```css |
| 550 | .htmx-request .htmx-indicator { transition: opacity 200ms ease-in 200ms; } |
| 551 | ``` |
| 552 | |
| 553 | If the request finishes before the delay elapses, the spinner never appears |
| 554 | |
| 555 | ### Disabling Elements During Request |
| 556 | |
| 557 | ```html |
| 558 | |
| 559 | <form hx-post="/save" hx-disable="find button, find input"> |
| 560 | <input name="data"> |
| 561 | <button type="submit">Save</button> |
| 562 | </form> |
| 563 | ``` |
| 564 | |
| 565 | ## Extensions |
| 566 | |
| 567 | Extensions are loaded by including the script file. They apply page-wide automatically: |
| 568 | |
| 569 | ```html |
| 570 | <script src="/path/to/hx-preload.js"></script> |
| 571 | ``` |
| 572 | |
| 573 | To restrict which extensions can load, use the `extensions` config as a whitelist: |
| 574 | |
| 575 | ```html |
| 576 | <meta name="htmx-config" content='{"extensions": "preload"}'> |
| 577 | ``` |
| 578 | |
| 579 | ## htmx 2 vs htmx 4: Practical Differences |
| 580 | |
| 581 | If you're unsure which version a project uses, check for `fetch()` usage in htmx source, the `:inherited` |
| 582 | modifier on attributes, or colon-separated event names like `htmx:after:swap`. These are all htmx 4 indicators. |
| 583 | |
| 584 | ### Attributes |
| 585 | |
| 586 | | htmx 2 | htmx 4 | Notes | |
| 587 | |--------------------------------------|---------------------------------------------------------------|---------------------------------------------------| |
| 588 | | `hx-disabled-elt` | `hx-disable` | Renamed | |
| 589 | | `hx-disable` (stops htmx processing) | `hx-ignore` | Different purpose in each version | |
| 590 | | `hx-ext="my-ext"` | Just include the script file | No attribute needed; config whitelist is optional | |
| 591 | | `hx-request='{"timeout":5000}'` | `hx-config='{"timeout":5000}'` | Renamed | |
| 592 | | `hx-prompt="Enter value"` | [`hx-prompt` extension](/extensions/hx-prompt) (same syntax), or [`hx-on::config:request` one-liner](/extensions/hx-prompt#without-the-extension) | Restored via extension | |
| 593 | | `hx-disinherit="*"` | Not needed | Inheritance is explicit by default in htmx 4 | |
| 594 | | `hx-vars` | `hx-vals` with `js:` prefix | hx-vars removed | |
| 595 | | Attributes inherit implicitly | Must use `:inherited` modifier | `hx-target:inherited="#out"` | |
| 596 | | `data-hx-get` works automatically | Requires `config.prefix = "data-hx-"` | Only `hx-*` by default in htmx 4 | |
| 597 | |
| 598 | htmx 4 adds: `hx-action`, `hx-method`, `hx-config`, `hx-status:XXX`, `hx-partial`, `:inherited` and `:append` modifiers. |
| 599 | |
| 600 | ### Events |
| 601 | |
| 602 | htmx 2 uses camelCase: `htmx:afterSwap`, `htmx:beforeRequest`, `htmx:configRequest`. |
| 603 | |
| 604 | htmx 4 uses colons: `htmx:after:swap`, `htmx:before:request`, `htmx:config:request`. |
| 605 | |
| 606 | Most error events (`htmx:sendError`, `htmx:swapError`, `htmx:targetError`, `htmx:timeout`) are consolidated into |
| 607 | `htmx:error` in htmx 4. HTTP error responses fire `htmx:response:error` (replacing `htmx:responseError`). |
| 608 | |
| 609 | ### Configuration |
| 610 | |
| 611 | | htmx 2 | htmx 4 | Notes | |
| 612 | |-------------------------------------|--------------------------------------|----------------------------------| |
| 613 | | `htmx.config.defaultSwapStyle` | `htmx.config.defaultSwap` | Renamed | |
| 614 | | `htmx.config.timeout = 0` | `htmx.config.defaultTimeout = 60000` | Renamed + default changed to 60s | |
| 615 | | `htmx.config.globalViewTransitions` | `htmx.config.transitions` | Renamed | |
| 616 | | `htmx.config.historyEnabled` | `htmx.config.history` | Renamed | |
| 617 | | `htmx.config.selfRequestsOnly` | `htmx.config.mode = 'same-origin'` | Different mechanism | |
| 618 | | `responseHandling` array | `htmx.config.noSwap` + `hx-status` | Simpler model | |
| 619 | | 4xx/5xx don't swap by default | All status codes swap except 204/304 | Major behavior change | |
| 620 | | History stored in localStorage | History does full page refresh | No more localStorage snapshots | |
| 621 | |
| 622 | ### JavaScript API |
| 623 | |
| 624 | | htmx 2 | htmx 4 | Notes | |
| 625 | |-----------------------------------------------|-----------------------------|----------------------------------| |
| 626 | | `htmx.defineExtension()` | `htmx.registerExtension()` | Renamed | |
| 627 | | `htmx.addClass()`, `htmx.removeClass()`, etc. | Native DOM methods | Removed; use `element.classList` | |
| 628 | | `htmx.off()` | `removeEventListener()` | Removed; use native | |
| 629 | | `htmx.remove()` | `element.remove()` | Removed; use native | |
| 630 | | `htmx.swap(target, content, spec)` | `htmx.swap(ctx)` | Signature changed | |
| 631 | |
| 632 | htmx 4 adds: `htmx.timeout()`. Logging now goes directly to `console.error` / `console.warn` / `console.log` (gated by `config.logAll` for events). `htmx.takeClass()` is **removed**; use `htmx.live.take()` (provided by the `hx-live` extension) or the unprefixed `take` helper inside expression scope. The `hx-live` extension also exposes `htmx.live.forEvent()`, `htmx.live.nextFrame()`, `htmx.live.q()`, `htmx.live.debounce()`, `htmx.live.refresh()`. |
| 633 | |
| 634 | ### Swap Styles |
| 635 | |
| 636 | htmx 4 adds `innerMorph`, `outerMorph`, `textContent`, and shorthand names (`before`, `after`, `prepend`, `append`). |
| 637 | |
| 638 | ### HTTP Headers |
| 639 | |
| 640 | | htmx 2 | htmx 4 | Notes | |
| 641 | |--------------------------------------|-------------|---------------------------------------------| |
| 642 | | `HX-Trigger` (request header) | `HX-Source` | Renamed; format changed from ID to `tag#id` | |
| 643 | | `HX-Trigger-Name` | Removed | Use `HX-Source` | |
| 644 | | `HX-Trigger-After-Swap` (response) | Removed | Use `HX-Trigger` | |
| 645 | | `HX-Trigger-After-Settle` (response) | Removed | Use `HX-Trigger` | |
| 646 | |
| 647 | htmx 4 adds: `HX-Request-Type` (`"full"` or `"partial"`). |
| 648 | |
| 649 | ### Extensions |
| 650 | |
| 651 | htmx 2: `hx-ext="my-extension"` attribute on elements, `htmx.defineExtension("name", {onEvent: ...})`. |
| 652 | |
| 653 | htmx 4: Just include the script. `htmx.registerExtension("name", {htmx_before_request: ...})`. Config whitelist optional. |
| 654 | Hook names use underscores (`htmx_before_swap`) instead of a single `onEvent` callback. |
| 655 | |
| 656 | ## Instructions for Claude |
| 657 | |
| 658 | When generating htmx code: |
| 659 | |
| 660 | 1. The general vibe with htmx is simplicity: a request returns HTML that is inserted into the DOM |
| 661 | 1. **Use `:inherited` modifier** for any attribute on a parent element intended for children |
| 662 | 1. **Server endpoints must return HTML fragments**, not JSON |
| 663 | 1. **Add loading indicators** for requests that may take time (`hx-indicator` + element with `htmx-indicator` class) |
| 664 | 1. **Use `hx-status:422`** for validation error handling -- server returns 422 with error HTML |
| 665 | 1. **Use morph swaps** when preserving form/input state matters. Use `innerHTML`/`outerHTML` for clean replacement |
| 666 | 1. **Prefer `<hx-partial>` tags** over `hx-swap-oob` for multi-region updates (more explicit) |
| 667 | 1. **GET and DELETE don't include form data** -- use `hx-include="closest form"` if needed |
| 668 | 1. When showing patterns, include both the HTML and describe what the server endpoint should return |
| 669 | 1. There are many useful extensions, for examples sse.js (Server Sent Events) for more dynamic situation and |
| 670 | hx-preload.js for speeding up navigational requests. Suggest them if they make sense. |