| 1 |
--- |
| 2 |
title: "Documentation" |
| 3 |
description: "From installation to advanced usage." |
| 4 |
--- |
| 5 |
import { Code } from 'astro:components'; |
| 6 |
import integrity from '../data/integrity.json'; |
| 7 |
import { codeBlockTransformer } from '../lib/shiki-transformers.js'; |
| 8 |
|
| 9 |
<hr data-sidebar-group="Get Started" /> |
| 10 |
|
| 11 |
## Installation |
| 12 |
|
| 13 |
htmx is a single JavaScript file with no dependencies. No build step is required to use it. |
| 14 |
|
| 15 |
### CDN |
| 16 |
|
| 17 |
Add this in your `<head>` tag: |
| 18 |
|
| 19 |
<Code lang="html" code={`<script src="https://cdn.jsdelivr.net/npm/htmx.org@${integrity.version}" integrity="${integrity.min}" crossorigin="anonymous"></script>`} theme="css-variables" transformers={[codeBlockTransformer]} /> |
| 20 |
|
| 21 |
#### Unminified |
| 22 |
|
| 23 |
<Code lang="html" code={`<script src="https://cdn.jsdelivr.net/npm/htmx.org@${integrity.version}/dist/htmx.js" integrity="${integrity.full}" crossorigin="anonymous"></script>`} theme="css-variables" transformers={[codeBlockTransformer]} /> |
| 24 |
|
| 25 |
#### ES Module |
| 26 |
|
| 27 |
<Code lang="html" code={`<script type="module" src="https://cdn.jsdelivr.net/npm/htmx.org@${integrity.version}/dist/htmx.esm.min.js" integrity="${integrity.esmMin}" crossorigin="anonymous"></script>`} theme="css-variables" transformers={[codeBlockTransformer]} /> |
| 28 |
|
| 29 |
#### ES Module (unminified) |
| 30 |
|
| 31 |
<Code lang="html" code={`<script type="module" src="https://cdn.jsdelivr.net/npm/htmx.org@${integrity.version}/dist/htmx.esm.js" integrity="${integrity.esm}" crossorigin="anonymous"></script>`} theme="css-variables" transformers={[codeBlockTransformer]} /> |
| 32 |
|
| 33 |
### Download |
| 34 |
|
| 35 |
Instead of using a CDN, consider [self-hosting in production](https://blog.wesleyac.com/posts/why-not-javascript-cdn). |
| 36 |
|
| 37 |
1. Download <a download href="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/htmx.min.js">htmx.min.js</a> |
| 38 |
2. Save it to your project (e.g., `/js/htmx.min.js`) |
| 39 |
3. Add this in your `<head>` tag: |
| 40 |
|
| 41 |
```html |
| 42 |
<script src="/js/htmx.min.js"></script> |
| 43 |
``` |
| 44 |
|
| 45 |
#### Other formats |
| 46 |
|
| 47 |
Download: <a download href="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/htmx.js">htmx.js</a> (unminified) |
| 48 |
|
| 49 |
Download: <a download href="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/htmx.esm.min.js">htmx.esm.min.js</a> (ES module) |
| 50 |
|
| 51 |
Download: <a download href="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/htmx.esm.js">htmx.esm.js</a> (ES module, unminified) |
| 52 |
|
| 53 |
### npm |
| 54 |
|
| 55 |
```sh |
| 56 |
npm install htmx.org@__VERSION__ |
| 57 |
``` |
| 58 |
|
| 59 |
```javascript |
| 60 |
import 'htmx.org'; |
| 61 |
``` |
| 62 |
|
| 63 |
#### Named import |
| 64 |
|
| 65 |
```javascript |
| 66 |
import htmx from 'htmx.org'; |
| 67 |
|
| 68 |
// Now you can use htmx.ajax(), htmx.find(), etc. |
| 69 |
``` |
| 70 |
|
| 71 |
### htmax |
| 72 |
|
| 73 |
The `htmax.js` file bundles htmx with the most popular extensions in a single file: |
| 74 |
|
| 75 |
* [SSE](/extensions/hx-sse) |
| 76 |
* [WebSockets](/extensions/hx-ws) |
| 77 |
* [preload](/extensions/hx-preload) |
| 78 |
* [browser-indicator](/extensions/hx-browser-indicator) |
| 79 |
* [download](/extensions/hx-download) |
| 80 |
* [optimistic](/extensions/hx-optimistic) |
| 81 |
* [targets](/extensions/hx-targets) |
| 82 |
* [live](/extensions/hx-live). |
| 83 |
|
| 84 |
The extensions are automatically available, you can just use their attributes directly (e.g. `hx-sse:connect`, `hx-ws:connect`). |
| 85 |
|
| 86 |
```html |
| 87 |
<script src="/js/htmax.min.js"></script> |
| 88 |
``` |
| 89 |
|
| 90 |
## Migration |
| 91 |
|
| 92 |
### Quick Migration |
| 93 |
|
| 94 |
There are two major behavioral changes between htmx 2.x and 4.x: |
| 95 |
|
| 96 |
* In htmx 2.0 attribute inheritance is *implicit* by default while in 4.0 it is explicit by default |
| 97 |
* In htmx 2.0, `400` and `500` response codes are not swapped by default, whereas in htmx 4.0 these requests will be |
| 98 |
swapped |
| 99 |
|
| 100 |
Add these two config lines to restore htmx 2.x behavior: |
| 101 |
|
| 102 |
```html |
| 103 |
|
| 104 |
<script> |
| 105 |
htmx.config.implicitInheritance = true; |
| 106 |
htmx.config.noSwap = [204, 304, '4xx', '5xx']; |
| 107 |
</script> |
| 108 |
<script src="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/htmx.min.js"></script> |
| 109 |
``` |
| 110 |
|
| 111 |
[`implicitInheritance`](/reference/config/htmx-config-implicitInheritance) restores htmx 2's implicit attribute |
| 112 |
inheritance. [`noSwap`](/reference/config/htmx-config-noSwap) prevents swapping error responses. |
| 113 |
|
| 114 |
Or load the [`htmx-2-compat`](/extensions/htmx-2-compat) extension, which restores implicit inheritance, old event |
| 115 |
names, and previous error-swapping defaults: |
| 116 |
|
| 117 |
```html |
| 118 |
|
| 119 |
<script src="/path/to/htmx.js"></script> |
| 120 |
<script src="/path/to/ext/htmx-2-compat.js"></script> |
| 121 |
``` |
| 122 |
|
| 123 |
Most htmx 2 apps should work with either approach. Then migrate incrementally using this guide. |
| 124 |
|
| 125 |
### Upgrade Checker |
| 126 |
|
| 127 |
htmx 4 ships with a command-line tool scans your templates and JS files for htmx 2 code that needs updating. It checks |
| 128 |
for removed attributes, old event names, inheritance patterns, extension changes, etc. |
| 129 |
|
| 130 |
```bash |
| 131 |
npx htmx.org@__VERSION__ upgrade-check -- ./path/to/project/root |
| 132 |
|
| 133 |
npx htmx.org@__VERSION__ upgrade-check --ext .vue ./path/to/project/root |
| 134 |
``` |
| 135 |
|
| 136 |
By default, the tool scans `.html`, `.php`, `.js`, `.ts`, `.jinja`, `.jinja2`, `.j2`, `.erb`, and `.hbs` files. |
| 137 |
|
| 138 |
Output is `file:line` format, clickable in most editors. You can add additional file types with the `--ext` option. |
| 139 |
|
| 140 |
The tool requires Python 3. |
| 141 |
|
| 142 |
### What Changed |
| 143 |
|
| 144 |
#### `fetch()` replaces `XMLHttpRequest` |
| 145 |
|
| 146 |
All requests use the native [`fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). This cannot be |
| 147 |
reverted. |
| 148 |
|
| 149 |
#### Explicit inheritance |
| 150 |
|
| 151 |
Add [`:inherited`](#attribute-inheritance) to any attribute that should inherit down the DOM tree. |
| 152 |
|
| 153 |
```html |
| 154 |
<!-- htmx 2: implicit inheritance --> |
| 155 |
<div hx-confirm="Are you sure?"> |
| 156 |
<button hx-delete="/item/1">Delete</button> |
| 157 |
</div> |
| 158 |
|
| 159 |
<!-- htmx 4: explicit inheritance --> |
| 160 |
<div hx-confirm:inherited="Are you sure?"> |
| 161 |
<button hx-delete="/item/1">Delete</button> |
| 162 |
</div> |
| 163 |
``` |
| 164 |
|
| 165 |
Works on any attribute: [`hx-boost`](/reference/attributes/hx-boost)`:inherited`, [ |
| 166 |
`hx-target`](/reference/attributes/hx-target)`:inherited`, [`hx-confirm`](/reference/attributes/hx-confirm)`:inherited`, |
| 167 |
etc. |
| 168 |
|
| 169 |
Use `:append` to add to an inherited value instead of replacing it: |
| 170 |
|
| 171 |
```html |
| 172 |
|
| 173 |
<div hx-include:inherited="#global-fields"> |
| 174 |
<!-- appends .extra to the inherited value --> |
| 175 |
<form hx-include:inherited:append=".extra">...</form> |
| 176 |
</div> |
| 177 |
``` |
| 178 |
|
| 179 |
Revert: [`htmx.config.implicitInheritance`](/reference/config/htmx-config-implicitInheritance) `= true` |
| 180 |
|
| 181 |
#### Error responses swap |
| 182 |
|
| 183 |
htmx 4 swaps all HTTP responses. Only [`204`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/204) |
| 184 |
and [`304`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/304) do not swap. |
| 185 |
|
| 186 |
htmx 2 did not swap `4xx` and `5xx` responses. In htmx 4, if your server returns HTML with a `422` or `500`, that HTML |
| 187 |
gets swapped into the target. Design your error responses to work as swap content, or use [ |
| 188 |
`hx-status`](/reference/attributes/hx-status) to control per-code behavior. |
| 189 |
|
| 190 |
Revert: [`htmx.config.noSwap`](/reference/config/htmx-config-noSwap) `= [204, 304, '4xx', '5xx']` |
| 191 |
|
| 192 |
#### [`hx-delete`](/reference/attributes/hx-delete) excludes form data |
| 193 |
|
| 194 |
Like [`hx-get`](/reference/attributes/hx-get), [`hx-delete`](/reference/attributes/hx-delete) no longer includes the |
| 195 |
enclosing form's inputs. |
| 196 |
|
| 197 |
Fix: add [`hx-include`](/reference/attributes/hx-include)`="closest form"` where needed. |
| 198 |
|
| 199 |
#### No history cache |
| 200 |
|
| 201 |
History no longer caches pages in [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). |
| 202 |
When navigating back, htmx re-fetches the page and swaps it into `<body>`, or into the `[hx-history-elt]` element if |
| 203 |
one is present, the same behavior as htmx 2. |
| 204 |
|
| 205 |
Use [`htmx.config.history`](/reference/config/htmx-config-history) `= "reload"` for a full page reload instead. Use |
| 206 |
`htmx.config.history = false` to disable. |
| 207 |
|
| 208 |
#### OOB swap order |
| 209 |
|
| 210 |
In htmx 2, out-of-band ([`hx-swap-oob`](/reference/attributes/hx-swap-oob)) elements swapped **before** the main |
| 211 |
content. |
| 212 |
|
| 213 |
In htmx 4, the main content swaps first. OOB and [`<hx-partial>`](#partials-hx-partial) elements swap after (in document order). |
| 214 |
|
| 215 |
This matters if an OOB swap creates or modifies DOM that the main swap depends on. If your app relies on that ordering, |
| 216 |
restructure so each swap is independent. |
| 217 |
|
| 218 |
#### `hx-trigger` `queue` modifier removed |
| 219 |
|
| 220 |
The `queue` modifier on [`hx-trigger`](/reference/attributes/hx-trigger) (e.g. `hx-trigger="click queue:all"`) no longer |
| 221 |
works. Request queuing is now controlled exclusively by [`hx-sync`](/reference/attributes/hx-sync). |
| 222 |
|
| 223 |
```html |
| 224 |
<!-- htmx 2 --> |
| 225 |
<div hx-trigger="click queue:all" hx-get="/test">...</div> |
| 226 |
|
| 227 |
<!-- htmx 4: use hx-sync instead --> |
| 228 |
<div hx-trigger="click" hx-get="/test" hx-sync="this:queue all">...</div> |
| 229 |
``` |
| 230 |
|
| 231 |
#### 60-second timeout |
| 232 |
|
| 233 |
htmx 2 had no timeout (`0`). htmx 4 sets [`defaultTimeout`](/reference/config/htmx-config-defaultTimeout) to `60000`. |
| 234 |
|
| 235 |
Revert: `htmx.config.defaultTimeout = 0` |
| 236 |
|
| 237 |
#### Extension loading |
| 238 |
|
| 239 |
Include extension scripts directly. No attribute needed: |
| 240 |
|
| 241 |
```html |
| 242 |
|
| 243 |
<script src="/path/to/htmx.js"></script> |
| 244 |
<script src="/path/to/ext/sse.js"></script> |
| 245 |
``` |
| 246 |
|
| 247 |
Restrict which extensions can load: |
| 248 |
|
| 249 |
```html |
| 250 |
|
| 251 |
<meta name="htmx-config" content='{"extensions": "sse, ws"}'> |
| 252 |
``` |
| 253 |
|
| 254 |
Extension authors use `htmx.registerExtension(name, methodMap)` to register. |
| 255 |
|
| 256 |
See [Extensions documentation](#extensions) for details. |
| 257 |
|
| 258 |
### Renames and Removals |
| 259 |
|
| 260 |
#### Rename `hx-disable` |
| 261 |
|
| 262 |
Do this **before** upgrading. The name `hx-disable` has been reassigned: |
| 263 |
|
| 264 |
- In htmx 2, `hx-disable` meant "skip htmx processing on this element" |
| 265 |
- In htmx 4, that role is [`hx-ignore`](/reference/attributes/hx-ignore) |
| 266 |
- The name `hx-disable` now does what `hx-disabled-elt` used to do (disable form elements during requests) |
| 267 |
|
| 268 |
Rename in this order to avoid conflicts: |
| 269 |
|
| 270 |
1. Rename `hx-disable` to [`hx-ignore`](/reference/attributes/hx-ignore) |
| 271 |
2. Rename `hx-disabled-elt` to [`hx-disable`](/reference/attributes/hx-disable) |
| 272 |
|
| 273 |
#### Removed attributes |
| 274 |
|
| 275 |
| Removed | Use instead | |
| 276 |
|------------------|---------------------------------------------------------------------------------------------------| |
| 277 |
| `hx-vars` | [`hx-vals`](/reference/attributes/hx-vals) with `js:` prefix | |
| 278 |
| `hx-params` | [`htmx:config:request`](/reference/events/htmx-config-request) event | |
| 279 |
| `hx-prompt` | [`hx-prompt` extension](/extensions/hx-prompt), or a [one-liner with `hx-on`](/extensions/hx-prompt#without-the-extension) | |
| 280 |
| `hx-ext` | [Include extension script directly](#extensions) | |
| 281 |
| `hx-disinherit` | Not needed (inheritance is explicit) | |
| 282 |
| `hx-inherit` | Not needed (inheritance is explicit) | |
| 283 |
| `hx-request` | [`hx-config`](/reference/attributes/hx-config) | |
| 284 |
| `hx-history` | Removed (no [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)) | |
| 285 |
|
| 286 |
#### Renamed events |
| 287 |
|
| 288 |
All events follow a new pattern: `htmx:phase:action[:sub-action]` |
| 289 |
|
| 290 |
Most error events are consolidated to [`htmx:error`](/reference/events/htmx-error). HTTP error responses have a dedicated [`htmx:response:error`](/reference/events/htmx-response-error) event. |
| 291 |
|
| 292 |
| htmx 2.x | htmx 4.x | |
| 293 |
|-----------------------------|-----------------------------------------------------------------------------------| |
| 294 |
| `htmx:afterOnLoad` | [`htmx:after:init`](/reference/events/htmx-after-init) | |
| 295 |
| `htmx:afterProcessNode` | [`htmx:after:init`](/reference/events/htmx-after-init) | |
| 296 |
| `htmx:afterRequest` | [`htmx:after:request`](/reference/events/htmx-after-request) | |
| 297 |
| `htmx:afterSettle` | [`htmx:after:swap`](/reference/events/htmx-after-swap) | |
| 298 |
| `htmx:afterSwap` | [`htmx:after:swap`](/reference/events/htmx-after-swap) | |
| 299 |
| `htmx:beforeCleanupElement` | [`htmx:before:cleanup`](/reference/events/htmx-before-cleanup) | |
| 300 |
| `htmx:beforeHistorySave` | [`htmx:before:history:update`](/reference/events/htmx-before-history-update) | |
| 301 |
| `htmx:beforeOnLoad` | [`htmx:before:init`](/reference/events/htmx-before-init) | |
| 302 |
| `htmx:beforeProcessNode` | [`htmx:before:process`](/reference/events/htmx-before-process) | |
| 303 |
| `htmx:beforeRequest` | [`htmx:before:request`](/reference/events/htmx-before-request) | |
| 304 |
| `htmx:beforeSwap` | [`htmx:before:swap`](/reference/events/htmx-before-swap) | |
| 305 |
| `htmx:configRequest` | [`htmx:config:request`](/reference/events/htmx-config-request) | |
| 306 |
| `htmx:historyCacheMiss` | [`htmx:before:history:restore`](/reference/events/htmx-before-restore-history) | |
| 307 |
| `htmx:historyRestore` | [`htmx:before:history:restore`](/reference/events/htmx-before-restore-history) | |
| 308 |
| `htmx:load` | [`htmx:after:init`](/reference/events/htmx-after-init) | |
| 309 |
| `htmx:oobAfterSwap` | [`htmx:after:swap`](/reference/events/htmx-after-swap) | |
| 310 |
| `htmx:oobBeforeSwap` | [`htmx:before:swap`](/reference/events/htmx-before-swap) | |
| 311 |
| `htmx:pushedIntoHistory` | [`htmx:after:history:push`](/reference/events/htmx-after-push-into-history) | |
| 312 |
| `htmx:replacedInHistory` | [`htmx:after:history:replace`](/reference/events/htmx-after-replace-into-history) | |
| 313 |
| `htmx:responseError` | [`htmx:response:error`](/reference/events/htmx-response-error) | |
| 314 |
| `htmx:sendError` | [`htmx:error`](/reference/events/htmx-error) | |
| 315 |
| `htmx:swapError` | [`htmx:error`](/reference/events/htmx-error) | |
| 316 |
| `htmx:targetError` | [`htmx:error`](/reference/events/htmx-error) | |
| 317 |
| `htmx:timeout` | [`htmx:error`](/reference/events/htmx-error) | |
| 318 |
|
| 319 |
#### Removed events |
| 320 |
|
| 321 |
Validation events are removed. Use native browser form validation: |
| 322 |
|
| 323 |
- `htmx:validation:validate` |
| 324 |
- `htmx:validation:failed` |
| 325 |
- `htmx:validation:halted` |
| 326 |
|
| 327 |
XHR events are removed (htmx uses `fetch()` now): |
| 328 |
|
| 329 |
| Removed | Use instead | |
| 330 |
|----------------------|------------------------------------------------------------------| |
| 331 |
| `htmx:xhr:loadstart` | No replacement | |
| 332 |
| `htmx:xhr:loadend` | [`htmx:finally:request`](/reference/events/htmx-finally-request) | |
| 333 |
| `htmx:xhr:progress` | No replacement | |
| 334 |
| `htmx:xhr:abort` | [`htmx:error`](/reference/events/htmx-error) | |
| 335 |
|
| 336 |
#### Config changes |
| 337 |
|
| 338 |
**Renamed:** |
| 339 |
|
| 340 |
| htmx 2.x | htmx 4.x | |
| 341 |
|--------------------------|----------------------------------------------------------------------------| |
| 342 |
| `defaultSwapStyle` | [`defaultSwap`](/reference/config/htmx-config-defaultSwap) | |
| 343 |
| `globalViewTransitions` | [`transitions`](/reference/config/htmx-config-transitions) | |
| 344 |
| `historyEnabled` | [`history`](/reference/config/htmx-config-history) | |
| 345 |
| `includeIndicatorStyles` | [`includeIndicatorCSS`](/reference/config/htmx-config-includeIndicatorCSS) | |
| 346 |
| `timeout` | [`defaultTimeout`](/reference/config/htmx-config-defaultTimeout) | |
| 347 |
|
| 348 |
**Changed defaults:** |
| 349 |
|
| 350 |
| Config | htmx 2 | htmx 4 | |
| 351 |
|--------------------------------------------------------------------------|------------------|----------------------| |
| 352 |
| [`defaultTimeout`](/reference/config/htmx-config-defaultTimeout) | `0` (no timeout) | `60000` (60 seconds) | |
| 353 |
| [`defaultSettleDelay`](/reference/config/htmx-config-defaultSettleDelay) | `20` | `1` | |
| 354 |
|
| 355 |
**Removed:** |
| 356 |
|
| 357 |
`addedClass`, `allowEval`, `allowNestedOobSwaps`, `allowScriptTags`, `attributesToSettle`, `defaultSwapDelay`, |
| 358 |
`disableSelector` (use [`hx-ignore`](/reference/attributes/hx-ignore)), `getCacheBusterParam`, `historyCacheSize`, |
| 359 |
`ignoreTitle` (still works per-swap via [`hx-swap`](/reference/attributes/hx-swap)`="... ignoreTitle:true"`), |
| 360 |
`inlineStyleNonce` (removed, indicator CSS now uses [Constructable Stylesheets](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/CSSStyleSheet) and does not require a nonce), |
| 361 |
`methodsThatUseUrlParams`, `refreshOnHistoryMiss`, `responseHandling` (use [ |
| 362 |
`hx-status`](/reference/attributes/hx-status) and [`noSwap`](/reference/config/htmx-config-noSwap)), `scrollBehavior`, |
| 363 |
`scrollIntoViewOnBoost`, `selfRequestsOnly` (use [`htmx.config.mode`](/reference/config/htmx-config-mode)), |
| 364 |
`settlingClass`, `swappingClass`, `triggerSpecsCache`, `useTemplateFragments`, `withCredentials` (use [ |
| 365 |
`hx-config`](/reference/attributes/hx-config)), `wsBinaryType`, `wsReconnectDelay` |
| 366 |
|
| 367 |
The `htmx-swapping`, `htmx-settling`, and `htmx-added` CSS classes are still applied during swaps. The config keys to |
| 368 |
customize their names have been removed. |
| 369 |
|
| 370 |
#### Request headers |
| 371 |
|
| 372 |
| htmx 2.x | htmx 4.x | Notes | |
| 373 |
|-------------------|---------------------------------------------------------|------------------------------------------------------------------------| |
| 374 |
| `HX-Trigger` | [`HX-Source`](/reference/headers/HX-Source) | Format changed to `tagName#id` (e.g. `button#submit`) | |
| 375 |
| `HX-Target` | [`HX-Target`](/reference/headers/HX-Target) | Format changed to `tagName#id` | |
| 376 |
| `HX-Trigger-Name` | removed | Use [`HX-Source`](/reference/headers/HX-Source) | |
| 377 |
| `HX-Prompt` | restored via extension | Load the [`hx-prompt`](/extensions/hx-prompt) extension | |
| 378 |
| *(new)* | [`HX-Request-Type`](/reference/headers/HX-Request-Type) | `"full"` or `"partial"` | |
| 379 |
| *(new)* | [`Accept`](/reference/headers/Accept) | Now explicitly `text/html` | |
| 380 |
|
| 381 |
#### Response headers |
| 382 |
|
| 383 |
Removed: |
| 384 |
|
| 385 |
- `HX-Trigger-After-Swap` |
| 386 |
- `HX-Trigger-After-Settle` |
| 387 |
|
| 388 |
Use [`HX-Trigger`](/reference/headers/HX-Trigger) or JavaScript instead. |
| 389 |
|
| 390 |
Unchanged: [`HX-Trigger`](/reference/headers/HX-Trigger), [`HX-Location`](/reference/headers/HX-Location), [ |
| 391 |
`HX-Push-Url`](/reference/headers/HX-Push-Url), [`HX-Redirect`](/reference/headers/HX-Redirect), [ |
| 392 |
`HX-Refresh`](/reference/headers/HX-Refresh), [`HX-Replace-Url`](/reference/headers/HX-Replace-Url), [ |
| 393 |
`HX-Retarget`](/reference/headers/HX-Retarget), [`HX-Reswap`](/reference/headers/HX-Reswap), [`HX-Reselect`](/reference/headers/HX-Reselect). |
| 394 |
|
| 395 |
#### JavaScript API changes |
| 396 |
|
| 397 |
**Removed methods.** Use native JavaScript: |
| 398 |
|
| 399 |
| htmx 2.x | Use instead | |
| 400 |
|----------------------|------------------------------------------------------------------------| |
| 401 |
| `htmx.addClass()` | `element.classList.add()` | |
| 402 |
| `htmx.removeClass()` | `element.classList.remove()` | |
| 403 |
| `htmx.toggleClass()` | `element.classList.toggle()` | |
| 404 |
| `htmx.closest()` | `element.closest()` | |
| 405 |
| `htmx.remove()` | `element.remove()` | |
| 406 |
| `htmx.off()` | `removeEventListener()` (`htmx.on()` returns the callback) | |
| 407 |
| `htmx.location()` | `htmx.ajax()` | |
| 408 |
|
| 409 |
**Renamed:** `htmx.defineExtension()` is now `htmx.registerExtension()`. |
| 410 |
|
| 411 |
**Still available:** `htmx.ajax()`, `htmx.config`, `htmx.find()`, `htmx.findAll()`, `htmx.on()`, |
| 412 |
`htmx.onLoad()`, `htmx.parseInterval()`, `htmx.process()`, `htmx.swap()`, `htmx.trigger()`. |
| 413 |
|
| 414 |
**Removed:** `htmx.logAll()`, `htmx.logNone()`, and the pluggable `htmx.logger`. htmx now logs directly via |
| 415 |
`console.error` / `console.warn` / `console.log`. Set `htmx.config.logAll = true` to surface event-level |
| 416 |
output. Observability tools (Sentry, DataDog RUM, LogRocket, etc.) capture `console.*` automatically. |
| 417 |
|
| 418 |
Note: `htmx.onLoad()` now listens on [`htmx:after:process`](/reference/events/htmx-after-process), not [ |
| 419 |
`htmx:after:init`](/reference/events/htmx-after-init). |
| 420 |
|
| 421 |
### What's New |
| 422 |
|
| 423 |
#### Attributes |
| 424 |
|
| 425 |
| Attribute | Purpose | |
| 426 |
|----------------------------------------------------|-----------------------------------------------------------------------| |
| 427 |
| [`hx-action`](/reference/attributes/hx-action) | Specify URL (use with [`hx-method`](/reference/attributes/hx-method)) | |
| 428 |
| [`hx-method`](/reference/attributes/hx-method) | Specify HTTP method | |
| 429 |
| [`hx-config`](/reference/attributes/hx-config) | Per-element request config (JSON or `key:value` syntax) | |
| 430 |
| [`hx-ignore`](/reference/attributes/hx-ignore) | Disable htmx processing (was `hx-disable`) | |
| 431 |
| [`hx-validate`](/reference/attributes/hx-validate) | Control form validation behavior | |
| 432 |
|
| 433 |
#### [`hx-swap`](/reference/attributes/hx-swap) scroll modifiers |
| 434 |
|
| 435 |
The `show` and `scroll` modifiers no longer support the combined `selector:position` syntax. Use separate keys instead: |
| 436 |
|
| 437 |
```html |
| 438 |
<!-- htmx 2 (broken in 4) --> |
| 439 |
<div hx-swap="innerHTML show:#other:top"></div> |
| 440 |
|
| 441 |
<!-- htmx 4 --> |
| 442 |
<div hx-swap="innerHTML show:top showTarget:#other"></div> |
| 443 |
<div hx-swap="innerHTML scroll:bottom scrollTarget:#other"></div> |
| 444 |
``` |
| 445 |
|
| 446 |
#### [`hx-swap`](/reference/attributes/hx-swap) styles |
| 447 |
|
| 448 |
```html |
| 449 |
|
| 450 |
<div hx-get="/data" hx-swap="innerMorph">...</div> |
| 451 |
<div hx-get="/data" hx-swap="outerMorph">...</div> |
| 452 |
<div hx-get="/text" hx-swap="textContent">...</div> |
| 453 |
<div hx-get="/remove" hx-swap="delete">...</div> |
| 454 |
``` |
| 455 |
|
| 456 |
- `innerMorph` / `outerMorph`: morph swaps using the idiomorph algorithm. Better for preserving state in complex UIs. |
| 457 |
- `textContent`: set the target's text content (no HTML parsing). |
| 458 |
- `delete`: remove the target element entirely. |
| 459 |
|
| 460 |
New aliases for existing swap styles (both old and new names work): |
| 461 |
|
| 462 |
| New | Equivalent to | |
| 463 |
|-----------|---------------| |
| 464 |
| `before` | `beforebegin` | |
| 465 |
| `after` | `afterend` | |
| 466 |
| `prepend` | `afterbegin` | |
| 467 |
| `append` | `beforeend` | |
| 468 |
|
| 469 |
#### [Status code swaps](/reference/attributes/hx-status) |
| 470 |
|
| 471 |
Set different swap behavior per HTTP status code: |
| 472 |
|
| 473 |
```html |
| 474 |
|
| 475 |
<form hx-post="/save" |
| 476 |
hx-status:422="swap:innerHTML target:#errors select:#validation-errors" |
| 477 |
hx-status:5xx="swap:none push:false"> |
| 478 |
<!-- form fields --> |
| 479 |
</form> |
| 480 |
``` |
| 481 |
|
| 482 |
Available config keys: `swap:`, `target:`, `select:`, `push:`, `replace:`, `transition:`. |
| 483 |
|
| 484 |
Supports exact codes (`404`), single-digit wildcards (`50x`), and range wildcards (`5xx`). Evaluated in order of |
| 485 |
specificity. |
| 486 |
|
| 487 |
#### `<hx-partial>` |
| 488 |
|
| 489 |
Target multiple elements from one response. An alternative to [`hx-swap-oob`](/reference/attributes/hx-swap-oob) for when you need explicit control over targeting and swap strategy: |
| 490 |
|
| 491 |
```html |
| 492 |
<hx-partial hx-target="#messages" hx-swap="beforeend"> |
| 493 |
<div>New message</div> |
| 494 |
</hx-partial> |
| 495 |
|
| 496 |
<hx-partial hx-target="#count"> |
| 497 |
<span>5</span> |
| 498 |
</hx-partial> |
| 499 |
``` |
| 500 |
|
| 501 |
Each `<hx-partial>` specifies its own [`hx-target`](/reference/attributes/hx-target) and [`hx-swap`](/reference/attributes/hx-swap) strategy. See [Multi-Target Updates](#multi-target-updates) for full documentation. |
| 502 |
|
| 503 |
#### View transitions |
| 504 |
|
| 505 |
[View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API) support is available but |
| 506 |
disabled by default. |
| 507 |
|
| 508 |
Enable: [`htmx.config.transitions`](/reference/config/htmx-config-transitions) `= true` |
| 509 |
|
| 510 |
#### JSX compatibility |
| 511 |
|
| 512 |
Frameworks that don't support `:` in attribute names can use [ |
| 513 |
`metaCharacter`](/reference/config/htmx-config-metaCharacter) to replace it: |
| 514 |
|
| 515 |
```js |
| 516 |
htmx.config.metaCharacter = "-"; |
| 517 |
// hx-ws-connect instead of hx-ws:connect |
| 518 |
// hx-confirm-inherited instead of hx-confirm:inherited |
| 519 |
``` |
| 520 |
|
| 521 |
#### JavaScript methods |
| 522 |
|
| 523 |
- `htmx.timeout(time)`: returns a promise that resolves after a delay (number ms, or interval string `'500ms'`/`'1s'`/`'5m'`) |
| 524 |
|
| 525 |
`htmx.takeClass` is **removed** from core. Equivalent functionality is exposed by the `hx-live` extension on the `htmx.live` namespace: |
| 526 |
|
| 527 |
```js |
| 528 |
htmx.live.take(target, className, source) // strip class from `source`, add to `target` |
| 529 |
htmx.live.forEvent(...args) // race events/timeouts |
| 530 |
htmx.live.nextFrame() // promise that resolves on next animation frame |
| 531 |
htmx.live.q(selector) // jQuery-like proxy rooted at documentElement |
| 532 |
htmx.live.debounce(ms[, fn]) // global debounce |
| 533 |
htmx.live.refresh() // recompute every live expression |
| 534 |
``` |
| 535 |
|
| 536 |
Inside `hx-live`/`hx-on` expression scope these are available unprefixed (`take`, `forEvent`, `nextFrame`, `q`, `debounce`, `toggle`) with the current element used as the implicit context, see the [`hx-live` extension docs](/extensions/hx-live). |
| 537 |
|
| 538 |
#### Auto-logged events |
| 539 |
|
| 540 |
Internally-dispatched events route to the console as follows: |
| 541 |
|
| 542 |
- If `detail.error` is set on the event, output goes to `console.error` (the Error instance is inlined first when applicable, so DevTools renders the stack). This covers request failures, hx-on handler exceptions, and other thrown paths. Apps that listen for `htmx:error` get the same data via the event. |
| 543 |
- If `detail.warn` is set, output goes to `console.warn`. |
| 544 |
- Otherwise, the event is logged at `console.log` (silent by default; set `htmx.config.logAll = true` to surface). |
| 545 |
|
| 546 |
This restores the htmx 2.x convention: if you want an internal failure path to show up in the console, fire an event with `detail.error` (or `detail.warn`); no per-site `console.error` needed. |
| 547 |
|
| 548 |
#### Request context |
| 549 |
|
| 550 |
All events provide a consistent `ctx` object with request/response information. |
| 551 |
|
| 552 |
#### Events |
| 553 |
|
| 554 |
| Event | Fires | |
| 555 |
|------------------------------------------------------------------------------|---------------------------------------------------| |
| 556 |
| [`htmx:after:cleanup`](/reference/events/htmx-after-cleanup) | After element cleanup | |
| 557 |
| [`htmx:after:history:update`](/reference/events/htmx-after-history-update) | After history update | |
| 558 |
| [`htmx:after:process`](/reference/events/htmx-after-process) | After element processing | |
| 559 |
| [`htmx:before:response`](/reference/events/htmx-before-response) | Before response body is read (cancellable) | |
| 560 |
| [`htmx:before:settle`](/reference/events/htmx-before-settle) | Before settle phase | |
| 561 |
| [`htmx:after:settle`](/reference/events/htmx-after-settle) | After settle phase | |
| 562 |
| [`htmx:before:viewTransition`](/reference/events/htmx-before-viewTransition) | Before a view transition starts (cancellable) | |
| 563 |
| [`htmx:after:viewTransition`](/reference/events/htmx-after-viewTransition) | After a view transition completes | |
| 564 |
| [`htmx:finally:request`](/reference/events/htmx-finally-request) | Always fires after a request (success or failure) | |
| 565 |
|
| 566 |
#### Config keys |
| 567 |
|
| 568 |
| Config | Default | Purpose | |
| 569 |
|------------------------------------------------------------------------|-----------------|---------------------------------------------------------------| |
| 570 |
| [`extensions`](/reference/config/htmx-config-extensions) | `''` | Comma-separated list of allowed extension names | |
| 571 |
| [`mode`](/reference/config/htmx-config-mode) | `'same-origin'` | Fetch mode (replaces `selfRequestsOnly`) | |
| 572 |
| [`inlineScriptNonce`](/reference/config/htmx-config-inlineScriptNonce) | `''` | Nonce for inline scripts | |
| 573 |
| [`metaCharacter`](/reference/config/htmx-config-metaCharacter) | `':'` | Separator character in attribute/event names | |
| 574 |
| [`morphIgnore`](/reference/config/htmx-config-morphIgnore) | `["data-htmx-powered"]` | Attribute name prefixes to preserve during morph | |
| 575 |
| [`morphScanLimit`](/reference/config/htmx-config-morphScanLimit) | | Max elements to scan during morph matching | |
| 576 |
| [`morphSkip`](/reference/config/htmx-config-morphSkip) | `'[hx-morph-skip]'` | CSS selector for elements to skip during morph | |
| 577 |
| [`morphSkipChildren`](/reference/config/htmx-config-morphSkipChildren) | `'[hx-morph-skip-children]'` | CSS selector for elements whose children to skip during morph | |
| 578 |
|
| 579 |
#### Core extensions |
| 580 |
|
| 581 |
htmx 4 ships with 9 core extensions. The SSE and WebSocket extensions have been significantly rewritten. See their upgrade guides for details. |
| 582 |
|
| 583 |
| Extension | Description | |
| 584 |
|-----------------------------------------------------------|--------------------------------------------------------------------------------------| |
| 585 |
| [`alpine-compat`](/extensions/hx-alpine-compat) | Alpine.js compatibility: initializes Alpine on fragments before swap | |
| 586 |
| [`browser-indicator`](/extensions/hx-browser-indicator) | Shows the browser's native loading indicator during requests | |
| 587 |
| [`head-support`](/extensions/hx-head) | Merges head tag information (styles, etc.) in htmx requests | |
| 588 |
| [`htmx-2-compat`](/extensions/htmx-2-compat) | Restores implicit inheritance, old event names, and previous error-swapping defaults | |
| 589 |
| [`optimistic`](/extensions/hx-optimistic) | Shows expected content from a template before the server responds | |
| 590 |
| [`preload`](/extensions/hx-preload) | Triggers requests early (on mouseover/mousedown) for near-instant page loads ([upgrade guide](/extensions/hx-preload#upgrading-from-htmx-2x)) | |
| 591 |
| [`sse`](/extensions/hx-sse) | Server-Sent Events streaming support ([upgrade guide](/extensions/hx-sse#upgrading-from-htmx-2x)) | |
| 592 |
| [`upsert`](/extensions/hx-upsert) | Updates existing elements by ID and inserts new ones, preserving unmatched elements | |
| 593 |
| [`ws`](/extensions/hx-ws) | Bi-directional WebSocket communication ([upgrade guide](/extensions/hx-ws#upgrading-from-htmx-2x)) | |
| 594 |
|
| 595 |
### Checklist |
| 596 |
|
| 597 |
1. Optionally, add config options or load [`htmx-2-compat`](/extensions/htmx-2-compat) for backward compatibility |
| 598 |
2. Run the [upgrade checker](#upgrade-checker) to get a full list of issues |
| 599 |
3. Rename `hx-disable` to [`hx-ignore`](/reference/attributes/hx-ignore), then `hx-disabled-elt` to [ |
| 600 |
`hx-disable`](/reference/attributes/hx-disable) |
| 601 |
4. Replace removed attributes with alternatives |
| 602 |
5. Find/replace event names in JavaScript and `hx-on` attributes |
| 603 |
6. Replace removed API methods with native JS |
| 604 |
7. Update extensions |
| 605 |
8. Rename changed config keys |
| 606 |
9. Test error handling (4xx/5xx now swap by default) |
| 607 |
10. Test attribute inheritance |
| 608 |
11. Test history navigation |
| 609 |
|
| 610 |
### Migration Notes |
| 611 |
|
| 612 |
Individual documentation pages include migration notes where features changed. |
| 613 |
|
| 614 |
Look for these: |
| 615 |
|
| 616 |
<details class="warning"> |
| 617 |
<summary>Changes in htmx 4.0</summary> |
| 618 |
|
| 619 |
</details> |
| 620 |
|
| 621 |
### Get Help |
| 622 |
|
| 623 |
- [GitHub Discussions](https://github.com/bigskysoftware/htmx/discussions) |
| 624 |
- [Discord](https://htmx.org/discord) |
| 625 |
- [Patterns](/patterns) |
| 626 |
|
| 627 |
|
| 628 |
### Migrating Your Own Extensions |
| 629 |
|
| 630 |
{/* Audience shifts here from htmx consumers to extension authors. */} |
| 631 |
|
| 632 |
If you maintain a custom extension written for htmx 2.x, the extension API has changed substantially. The catalog of bundled extensions ([/extensions](/extensions)) has already been ported. This section is for porting your own. |
| 633 |
|
| 634 |
#### From Callbacks to Hooks |
| 635 |
|
| 636 |
htmx 4 replaces the callback-based extension API with event-based hooks. Extensions register handlers for lifecycle events instead of implementing callback methods. |
| 637 |
|
| 638 |
The simplest migration: rename `defineExtension` to `registerExtension` and map your callbacks to hooks. |
| 639 |
|
| 640 |
```javascript |
| 641 |
// htmx 2.x |
| 642 |
htmx.defineExtension('my-ext', { |
| 643 |
onEvent: function(name, evt) { |
| 644 |
if (name === 'htmx:beforeRequest') { /* ... */ } |
| 645 |
} |
| 646 |
}); |
| 647 |
|
| 648 |
// htmx 4 |
| 649 |
htmx.registerExtension('my-ext', { |
| 650 |
htmx_before_request: (elt, detail) => { /* ... */ } |
| 651 |
}); |
| 652 |
``` |
| 653 |
|
| 654 |
#### What Changed |
| 655 |
|
| 656 |
##### No `hx-ext` attribute |
| 657 |
|
| 658 |
Extensions load by including the script. No attribute needed: |
| 659 |
|
| 660 |
```html |
| 661 |
<script src="/path/to/htmx.js"></script> |
| 662 |
<script src="/path/to/ext/my-extension.js"></script> |
| 663 |
``` |
| 664 |
|
| 665 |
Restrict which extensions can load: |
| 666 |
|
| 667 |
```html |
| 668 |
<meta name="htmx-config" content='{"extensions": "sse, ws"}'> |
| 669 |
``` |
| 670 |
|
| 671 |
##### Event hooks replace callbacks |
| 672 |
|
| 673 |
Instead of a single `onEvent` callback that switches on event names, each event gets its own hook method. Hook names use underscores where events use colons: |
| 674 |
|
| 675 |
| htmx 2.x event | htmx 4 hook | |
| 676 |
|---|---| |
| 677 |
| `htmx:configRequest` | `htmx_config_request` | |
| 678 |
| `htmx:beforeRequest` | `htmx_before_request` | |
| 679 |
| `htmx:afterRequest` | `htmx_after_request` | |
| 680 |
| `htmx:beforeSwap` | `htmx_before_swap` | |
| 681 |
| `htmx:afterSwap` | `htmx_after_swap` | |
| 682 |
|
| 683 |
All hooks receive `(elt, detail)`. Return `false` to cancel. |
| 684 |
|
| 685 |
##### `handle_swap` is special |
| 686 |
|
| 687 |
Unlike other hooks, `handle_swap` is called directly with positional parameters (no `htmx_` prefix, no detail object): |
| 688 |
|
| 689 |
```javascript |
| 690 |
handle_swap: (swapStyle, target, fragment, swapSpec) => { |
| 691 |
if (swapStyle === 'my-swap') { |
| 692 |
target.appendChild(fragment); |
| 693 |
return true; |
| 694 |
} |
| 695 |
return false; |
| 696 |
} |
| 697 |
``` |
| 698 |
|
| 699 |
##### Detail object replaces event properties |
| 700 |
|
| 701 |
All hooks receive `detail.ctx` with full request/response context: |
| 702 |
|
| 703 |
- `detail.ctx.request.body` (FormData in `htmx_config_request`) |
| 704 |
- `detail.ctx.request.headers` |
| 705 |
- `detail.ctx.response.status` |
| 706 |
- `detail.ctx.text` (response body, modifiable in `htmx_after_request`) |
| 707 |
- `detail.ctx.target` |
| 708 |
|
| 709 |
##### OOB swap stripping |
| 710 |
|
| 711 |
OOB swaps automatically strip the wrapper element for non-outer swap styles. Name custom swap styles starting with "outer" (e.g., `outerMorph`) to preserve the wrapper. |
| 712 |
|
| 713 |
#### Callback Migration Map |
| 714 |
|
| 715 |
##### `init` |
| 716 |
|
| 717 |
```javascript |
| 718 |
// htmx 2.x |
| 719 |
init: function(api) { |
| 720 |
return null; |
| 721 |
} |
| 722 |
|
| 723 |
// htmx 4 |
| 724 |
init: (internalAPI) => { |
| 725 |
api = internalAPI; |
| 726 |
} |
| 727 |
``` |
| 728 |
|
| 729 |
Store the `internalAPI` reference for use in other hooks. No return value needed. |
| 730 |
|
| 731 |
##### `getSelectors` |
| 732 |
|
| 733 |
Removed. Use `htmx_after_init` to check for attributes: |
| 734 |
|
| 735 |
```javascript |
| 736 |
// htmx 2.x |
| 737 |
getSelectors: function() { |
| 738 |
return ['[my-custom-attr]']; |
| 739 |
}, |
| 740 |
onEvent: function(name, evt) { |
| 741 |
if (name === 'htmx:afterProcessNode') { |
| 742 |
initializeCustomBehavior(evt.target); |
| 743 |
} |
| 744 |
} |
| 745 |
|
| 746 |
// htmx 4 |
| 747 |
htmx_after_init: (elt) => { |
| 748 |
if (api.attributeValue(elt, 'my-custom-attr')) { |
| 749 |
initializeCustomBehavior(elt); |
| 750 |
} |
| 751 |
} |
| 752 |
``` |
| 753 |
|
| 754 |
##### `onEvent` |
| 755 |
|
| 756 |
Replace with individual hooks: |
| 757 |
|
| 758 |
```javascript |
| 759 |
// htmx 2.x |
| 760 |
onEvent: function(name, evt) { |
| 761 |
if (name === 'htmx:beforeSwap' && evt.detail.xhr.status !== 200) { |
| 762 |
var target = getRespCodeTarget(evt.detail.requestConfig.elt, evt.detail.xhr.status); |
| 763 |
if (target) { |
| 764 |
evt.detail.shouldSwap = true; |
| 765 |
evt.detail.target = target; |
| 766 |
} |
| 767 |
} |
| 768 |
} |
| 769 |
|
| 770 |
// htmx 4 |
| 771 |
htmx_before_swap: (elt, detail) => { |
| 772 |
if (detail.ctx.response.status !== 200) { |
| 773 |
var target = getRespCodeTarget(elt, detail.ctx.response.status); |
| 774 |
if (target) { |
| 775 |
detail.ctx.target = target; |
| 776 |
} |
| 777 |
} |
| 778 |
} |
| 779 |
``` |
| 780 |
|
| 781 |
##### `transformResponse` |
| 782 |
|
| 783 |
Removed. Modify `detail.ctx.text` in `htmx_after_request`: |
| 784 |
|
| 785 |
```javascript |
| 786 |
// htmx 2.x |
| 787 |
transformResponse: function(text, xhr, elt) { |
| 788 |
var tpl = htmx.closest(elt, '[mustache-template]'); |
| 789 |
if (tpl) { |
| 790 |
var data = JSON.parse(text); |
| 791 |
var template = htmx.find('#' + tpl.getAttribute('mustache-template')); |
| 792 |
return Mustache.render(template.innerHTML, data); |
| 793 |
} |
| 794 |
return text; |
| 795 |
} |
| 796 |
|
| 797 |
// htmx 4 |
| 798 |
htmx_after_request: (elt, detail) => { |
| 799 |
var tpl = elt.closest('[mustache-template]'); |
| 800 |
if (tpl) { |
| 801 |
var data = JSON.parse(detail.ctx.text); |
| 802 |
var template = document.querySelector('#' + tpl.getAttribute('mustache-template')); |
| 803 |
detail.ctx.text = Mustache.render(template.innerHTML, data); |
| 804 |
} |
| 805 |
} |
| 806 |
``` |
| 807 |
|
| 808 |
Event flow: response received, `ctx.text` set, `htmx:after:request` fires, `ctx.text` consumed into fragment, `htmx:before:swap`. |
| 809 |
|
| 810 |
##### `encodeParameters` |
| 811 |
|
| 812 |
Removed. Modify `detail.ctx.request.body` in `htmx_config_request`: |
| 813 |
|
| 814 |
```javascript |
| 815 |
// htmx 2.x |
| 816 |
onEvent: function(name, evt) { |
| 817 |
if (name === 'htmx:configRequest') { |
| 818 |
evt.detail.headers['Content-Type'] = 'application/json'; |
| 819 |
} |
| 820 |
}, |
| 821 |
encodeParameters: function(xhr, parameters, elt) { |
| 822 |
var object = {}; |
| 823 |
parameters.forEach(function(value, key) { |
| 824 |
if (Object.hasOwn(object, key)) { |
| 825 |
if (!Array.isArray(object[key])) object[key] = [object[key]]; |
| 826 |
object[key].push(value); |
| 827 |
} else { |
| 828 |
object[key] = value; |
| 829 |
} |
| 830 |
}); |
| 831 |
return JSON.stringify(object); |
| 832 |
} |
| 833 |
|
| 834 |
// htmx 4 |
| 835 |
htmx_config_request: (elt, detail) => { |
| 836 |
detail.ctx.request.headers['Content-Type'] = 'application/json'; |
| 837 |
var object = {}; |
| 838 |
detail.ctx.request.body.forEach(function(value, key) { |
| 839 |
if (Object.hasOwn(object, key)) { |
| 840 |
if (!Array.isArray(object[key])) object[key] = [object[key]]; |
| 841 |
object[key].push(value); |
| 842 |
} else { |
| 843 |
object[key] = value; |
| 844 |
} |
| 845 |
}); |
| 846 |
detail.ctx.request.body = JSON.stringify(object); |
| 847 |
} |
| 848 |
``` |
| 849 |
|
| 850 |
`ctx.request.body` is FormData in `htmx_config_request`. It can be replaced with any value (string, JSON, URLSearchParams). For GET/DELETE, body becomes query parameters. For POST/PUT/PATCH, body becomes URLSearchParams (unless multipart). |
| 851 |
|
| 852 |
##### `isInlineSwap` and `handleSwap` |
| 853 |
|
| 854 |
Both replaced by `handle_swap`: |
| 855 |
|
| 856 |
```javascript |
| 857 |
// htmx 2.x |
| 858 |
isInlineSwap: function(swapStyle) { |
| 859 |
return swapStyle === 'morphdom'; |
| 860 |
}, |
| 861 |
handleSwap: function(swapStyle, target, fragment) { |
| 862 |
if (swapStyle === 'morphdom') { |
| 863 |
morphdom(target, fragment.firstElementChild || fragment.firstChild); |
| 864 |
return [target]; |
| 865 |
} |
| 866 |
} |
| 867 |
|
| 868 |
// htmx 4 |
| 869 |
handle_swap: (swapStyle, target, fragment) => { |
| 870 |
if (swapStyle === 'morphdom') { |
| 871 |
morphdom(target, fragment.firstElementChild || fragment.firstChild); |
| 872 |
return true; |
| 873 |
} |
| 874 |
return false; |
| 875 |
} |
| 876 |
``` |
| 877 |
|
| 878 |
Return truthy if handled, falsy otherwise. Can return an array of elements for settle tracking. |
| 879 |
|
| 880 |
#### Removed Callbacks |
| 881 |
|
| 882 |
| htmx 2.x callback | htmx 4 replacement | |
| 883 |
|-----------------------------------------|---------------------------------------------------------------| |
| 884 |
| `getSelectors()` | `htmx_after_init` hook | |
| 885 |
| `onEvent(name, evt)` | Individual `htmx_*` hooks | |
| 886 |
| `transformResponse(text, xhr, elt)` | `htmx_after_request` hook (modify `detail.ctx.text`) | |
| 887 |
| `encodeParameters(xhr, params, elt)` | `htmx_config_request` hook (modify `detail.ctx.request.body`) | |
| 888 |
| `isInlineSwap(swapStyle)` | `handle_swap` or name swap style with "outer" prefix | |
| 889 |
| `handleSwap(style, target, frag, info)` | `handle_swap(style, target, frag, spec)` | |
| 890 |
|
| 891 |
#### Checklist |
| 892 |
|
| 893 |
1. Rename `defineExtension` to `registerExtension` |
| 894 |
2. Replace `onEvent` with individual `htmx_*` hooks |
| 895 |
3. Replace `transformResponse` with `htmx_after_request` |
| 896 |
4. Replace `encodeParameters` with `htmx_config_request` |
| 897 |
5. Merge `isInlineSwap` and `handleSwap` into `handle_swap` |
| 898 |
6. Replace `getSelectors` with `htmx_after_init` |
| 899 |
7. Remove `hx-ext` attributes from HTML |
| 900 |
8. Update event names (colons to underscores in hook names) |
| 901 |
9. Test custom swap styles with OOB swaps |
| 902 |
|
| 903 |
<hr data-sidebar-group="Core Concepts" /> |
| 904 |
|
| 905 |
## Mental Model |
| 906 |
|
| 907 |
{/* TODO: Add section for developers coming from React/Vue/Svelte - |
| 908 |
cover the mindset shift from "client builds UI from JSON" to |
| 909 |
"server sends ready-to-render HTML". Address common misconceptions |
| 910 |
and patterns to unlearn. */} |
| 911 |
|
| 912 |
htmx extends HTML's built-in concept of [hypermedia controls](https://dl.acm.org/doi/fullHtml/10.1145/3648188.3675127). |
| 913 |
|
| 914 |
To understand htmx, you should first understand what these are. |
| 915 |
|
| 916 |
### HTML's Native Controls |
| 917 |
|
| 918 |
HTML has two major elements that issue HTTP requests in response to user actions: `<a>` (anchors, aka "links") and |
| 919 |
`<form>`. |
| 920 |
|
| 921 |
#### The Anchor Tag |
| 922 |
|
| 923 |
```html |
| 924 |
<a href="/blog">Blog</a> |
| 925 |
``` |
| 926 |
|
| 927 |
When a user click this link a browser will issue an HTTP `GET` request to `/blog`. It will then load the HTML response |
| 928 |
into the browser's window. |
| 929 |
|
| 930 |
#### The Form Tag |
| 931 |
|
| 932 |
```html |
| 933 |
|
| 934 |
<form method="post" action="/register"> |
| 935 |
<label>Email: <input type="email"></label> |
| 936 |
<button type="submit">Submit</button> |
| 937 |
</form> |
| 938 |
``` |
| 939 |
|
| 940 |
When a user submits this form (by, say, clicking on the "Submit" button) a browser will issue an HTTP `POST` request to |
| 941 |
`/register`. Again, it will load the HTML response to this request into the browser window. |
| 942 |
|
| 943 |
These two hypermedia controls demonstrate the core idea behind them: in response to a user action a |
| 944 |
request is made and new content is loaded into the client. |
| 945 |
|
| 946 |
### Transclusion |
| 947 |
|
| 948 |
Both of these HTML elements support a (relatively little-known and unused) |
| 949 |
[`target`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/target) attribute. |
| 950 |
|
| 951 |
By using this attribute you can place the response in, for example, an iframe rather than replacing the entire |
| 952 |
content in the window: |
| 953 |
|
| 954 |
```html |
| 955 |
|
| 956 |
<form method="post" action="/register" target="iframe1"> |
| 957 |
<label>Email: <input type="email"></label> |
| 958 |
<button type="submit">Submit</button> |
| 959 |
</form> |
| 960 |
<iframe name="iframe1"> |
| 961 |
<!-- Response appears here --> |
| 962 |
</iframe> |
| 963 |
``` |
| 964 |
|
| 965 |
This is [transclusion](https://en.wikipedia.org/wiki/Transclusion), where one HTML document is included inside of |
| 966 |
another. |
| 967 |
|
| 968 |
### How htmx Extends This Idea |
| 969 |
|
| 970 |
htmx generalizes these concepts. Any element can issue any type of HTTP request to any URL. Any event can trigger the |
| 971 |
request. And the response HTML can be placed anywhere in the DOM. |
| 972 |
|
| 973 |
```html |
| 974 |
|
| 975 |
<button hx-post="/clicked" |
| 976 |
hx-trigger="click" |
| 977 |
hx-target="#output" |
| 978 |
hx-swap="outerHTML"> |
| 979 |
Click Me |
| 980 |
</button> |
| 981 |
<output id="output"></output> |
| 982 |
``` |
| 983 |
|
| 984 |
These htmx attributes (which start with `hx-`) tell a browser: |
| 985 |
|
| 986 |
> When a user clicks this button, issue a POST request to `/clicked`. Use the response to replace the element with id |
| 987 |
`output`. |
| 988 |
|
| 989 |
Like anchor and form tags, htmx expects _HTML responses_ from the server. |
| 990 |
|
| 991 |
This is in contrast with many front-end libraries and frameworks today which instead expect JSON and |
| 992 |
use client-side templating to transform that JSON into HTML on the client. |
| 993 |
|
| 994 |
### htmx's Philosophy |
| 995 |
|
| 996 |
Because htmx works in terms of HTML it follows the [original web programming model](https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm). |
| 997 |
It uses [Hypertext As The Engine Of Application State](https://en.wikipedia.org/wiki/HATEOAS) (HATEOAS). |
| 998 |
|
| 999 |
The server controls what the user sees by sending HTML. Users select actions from that HTML and the server responds with |
| 1000 |
more HTML (i.e. hypertext). |
| 1001 |
|
| 1002 |
Thus, the hypermedia itself drives the application. |
| 1003 |
|
| 1004 |
## Hypermedia Controls |
| 1005 |
|
| 1006 |
htmx extends HTML with attributes that control how requests are made and how responses update the page. |
| 1007 |
|
| 1008 |
### Making Requests |
| 1009 |
|
| 1010 |
Add [`hx-get`](/reference/attributes/hx-get) to an element. It makes an AJAX request when clicked. |
| 1011 |
|
| 1012 |
**Your HTML:** |
| 1013 |
```html |
| 1014 |
<button hx-get="/messages"> |
| 1015 |
Load Messages |
| 1016 |
</button> |
| 1017 |
``` |
| 1018 |
|
| 1019 |
**What the server returns:** |
| 1020 |
```html |
| 1021 |
<div>You have 3 new messages</div> |
| 1022 |
``` |
| 1023 |
|
| 1024 |
**What the user sees:** |
| 1025 |
```html |
| 1026 |
<button hx-get="/messages"> |
| 1027 |
<div>You have 3 new messages</div> |
| 1028 |
</button> |
| 1029 |
``` |
| 1030 |
|
| 1031 |
The response replaced the button's content. No JavaScript required. |
| 1032 |
|
| 1033 |
#### How It Works |
| 1034 |
|
| 1035 |
| Step | What Happens | |
| 1036 |
|-----------------------|----------------------------------| |
| 1037 |
| 1. User clicks button | htmx intercepts the click | |
| 1038 |
| 2. htmx makes request | Sends GET request to `/messages` | |
| 1039 |
| 3. Server responds | Returns HTML (not JSON) | |
| 1040 |
| 4. htmx updates page | Swaps HTML into the button | |
| 1041 |
|
| 1042 |
#### HTTP Methods |
| 1043 |
|
| 1044 |
Use different attributes for different operations: |
| 1045 |
|
| 1046 |
```html |
| 1047 |
<button hx-get="/users">Load Users</button> |
| 1048 |
<button hx-post="/users">Create User</button> |
| 1049 |
<button hx-put="/users/1">Update User</button> |
| 1050 |
<button hx-patch="/users/1">Patch User</button> |
| 1051 |
<button hx-delete="/users/1">Delete User</button> |
| 1052 |
``` |
| 1053 |
|
| 1054 |
Each attribute combines the URL and HTTP method. |
| 1055 |
|
| 1056 |
#### Common Patterns |
| 1057 |
|
| 1058 |
**Load data on click:** |
| 1059 |
```html |
| 1060 |
<button hx-get="/profile">View Profile</button> |
| 1061 |
``` |
| 1062 |
|
| 1063 |
**Submit a form:** |
| 1064 |
```html |
| 1065 |
<form hx-post="/contact"> |
| 1066 |
<input name="email" type="email"> |
| 1067 |
<button type="submit">Send</button> |
| 1068 |
</form> |
| 1069 |
``` |
| 1070 |
|
| 1071 |
Form submits via AJAX instead of full page reload. |
| 1072 |
|
| 1073 |
**Delete an item:** |
| 1074 |
```html |
| 1075 |
<button hx-delete="/items/5">Delete Item</button> |
| 1076 |
``` |
| 1077 |
|
| 1078 |
#### What Gets Sent |
| 1079 |
|
| 1080 |
htmx sends standard HTTP requests: |
| 1081 |
|
| 1082 |
**Request to server:** |
| 1083 |
``` |
| 1084 |
GET /messages HTTP/1.1 |
| 1085 |
HX-Request: true |
| 1086 |
HX-Target: button |
| 1087 |
``` |
| 1088 |
|
| 1089 |
htmx adds custom headers so your server knows it's an htmx request. |
| 1090 |
|
| 1091 |
**Server response:** |
| 1092 |
```html |
| 1093 |
HTTP/1.1 200 OK |
| 1094 |
Content-Type: text/html |
| 1095 |
|
| 1096 |
<div>You have 3 new messages</div> |
| 1097 |
``` |
| 1098 |
|
| 1099 |
Just HTML. No JSON parsing needed. |
| 1100 |
|
| 1101 |
### Triggers |
| 1102 |
|
| 1103 |
By default, requests are triggered by the "natural" event of an element: |
| 1104 |
|
| 1105 |
* `input`, `textarea` & `select` are triggered on the `change` event |
| 1106 |
* `form` is triggered on the `submit` event |
| 1107 |
* everything else is triggered by the `click` event |
| 1108 |
|
| 1109 |
If you want different behavior you can use the [`hx-trigger`](/reference/attributes/hx-trigger) |
| 1110 |
attribute to specify which event will cause the request. |
| 1111 |
|
| 1112 |
Here is a `div` that posts to `/mouse_entered` when a mouse enters it: |
| 1113 |
|
| 1114 |
```html |
| 1115 |
<div hx-post="/mouse_entered" hx-trigger="mouseenter"> |
| 1116 |
Mouse Trap |
| 1117 |
</div> |
| 1118 |
``` |
| 1119 |
|
| 1120 |
#### Trigger Modifiers |
| 1121 |
|
| 1122 |
A trigger can also have additional modifiers that change its behavior. For example, if you want a request to only |
| 1123 |
happen once, you can use the `once` modifier for the trigger: |
| 1124 |
|
| 1125 |
```html |
| 1126 |
<div hx-post="/mouse_entered" hx-trigger="mouseenter once"> |
| 1127 |
Mouse Trap |
| 1128 |
</div> |
| 1129 |
``` |
| 1130 |
|
| 1131 |
Other modifiers you can use for triggers are (parsed as [HCON](#hcon)): |
| 1132 |
|
| 1133 |
* `changed` - only issue a request if the value of the element has changed |
| 1134 |
* `delay:<time interval>` - wait the given amount of time (e.g. `1s`) before |
| 1135 |
issuing the request. If the event triggers again, the countdown is reset. |
| 1136 |
* `throttle:<time interval>` - wait the given amount of time (e.g. `1s`) before |
| 1137 |
issuing the request. Unlike `delay` if a new event occurs before the time limit is hit the event will be discarded, |
| 1138 |
so the request will trigger at the end of the time period. |
| 1139 |
* `from:<CSS Selector>` - listen for the event on a different element. This can be used for things like keyboard |
| 1140 |
shortcuts. Note that this CSS selector is not re-evaluated if the page changes. |
| 1141 |
|
| 1142 |
Multiple triggers can be specified in the [`hx-trigger`](/reference/attributes/hx-trigger) attribute, separated by commas. |
| 1143 |
|
| 1144 |
You can use these features to implement many common UX patterns, such as [Active Search](/patterns/forms/active-search): |
| 1145 |
|
| 1146 |
```html |
| 1147 |
<input type="text" |
| 1148 |
name="q" |
| 1149 |
placeholder="Search..." |
| 1150 |
hx-get="/search" |
| 1151 |
hx-trigger="input delay:500ms, keyup[key=='Enter']" |
| 1152 |
hx-target="#search-results"> |
| 1153 |
<div id="search-results"></div> |
| 1154 |
``` |
| 1155 |
|
| 1156 |
This input will issue a request 500 milliseconds after an input event occurs, or the `enter` key is pressed and inserts |
| 1157 |
the results into the `div` with the id `search-results`. |
| 1158 |
|
| 1159 |
#### Trigger Filters |
| 1160 |
|
| 1161 |
In the example above, you may have noticed the square brackets after the event name. This is called a "trigger filter". |
| 1162 |
|
| 1163 |
Trigger filters allow you to place a filtering javascript expression after the event name that will prevent the trigger |
| 1164 |
if the filter does not return true. |
| 1165 |
|
| 1166 |
Here is an example that triggers only on a Shift-Click of the element |
| 1167 |
|
| 1168 |
```html |
| 1169 |
<div hx-get="/shift_clicked" hx-trigger="click[shiftKey]"> |
| 1170 |
Shift Click Me |
| 1171 |
</div> |
| 1172 |
``` |
| 1173 |
|
| 1174 |
Properties like `shiftKey` will be resolved against the triggering event first, then against the global scope. |
| 1175 |
|
| 1176 |
The `this` symbol will be set to the current element. |
| 1177 |
|
| 1178 |
#### Special Events |
| 1179 |
|
| 1180 |
htmx provides a few special events for use in [`hx-trigger`](/reference/attributes/hx-trigger): |
| 1181 |
|
| 1182 |
* `load` - fires once when the element is first loaded |
| 1183 |
* `revealed` - fires once when an element first scrolls into the viewport |
| 1184 |
* `intersect` - fires once when an element first intersects the viewport. This supports two additional options: |
| 1185 |
* `root:<selector>` - a CSS selector of the root element for intersection |
| 1186 |
* `threshold:<float>` - a floating point number between 0.0 and 1.0, indicating what amount of intersection to fire |
| 1187 |
the event on |
| 1188 |
|
| 1189 |
You can also use custom events to trigger requests. |
| 1190 |
|
| 1191 |
#### Polling |
| 1192 |
|
| 1193 |
Polling is a simple technique where a web page periodically issues a request to the server to see if any updates have |
| 1194 |
occurred. It is not very highly respected in many web development circles, but it is simple, can be relatively |
| 1195 |
resource-light because it does not maintain a constant network connection, and it tolerates network failures well |
| 1196 |
|
| 1197 |
In htmx you can implement polling via the `every` syntax in the [`hx-trigger`](/reference/attributes/hx-trigger) attribute: |
| 1198 |
|
| 1199 |
```html |
| 1200 |
<div hx-get="/news" hx-trigger="every 2s"></div> |
| 1201 |
``` |
| 1202 |
|
| 1203 |
This tells htmx: |
| 1204 |
|
| 1205 |
> Every 2 seconds, issue a GET to /news and load the response into the div |
| 1206 |
|
| 1207 |
#### Load Polling |
| 1208 |
|
| 1209 |
Another technique that can be used to achieve polling in htmx is "load polling", where an element specifies |
| 1210 |
a `load` trigger along with a delay, and replaces itself with the response: |
| 1211 |
|
| 1212 |
```html |
| 1213 |
<div hx-get="/messages" |
| 1214 |
hx-trigger="load delay:1s" |
| 1215 |
hx-swap="outerHTML"> |
| 1216 |
</div> |
| 1217 |
``` |
| 1218 |
|
| 1219 |
If the `/messages` end point keeps returning a div set up this way, it will keep "polling" back to the URL every |
| 1220 |
second. |
| 1221 |
|
| 1222 |
Load polling can be useful in situations where a poll has an end point at which point the polling terminates, such as |
| 1223 |
when you are showing the user a [progress bar](/patterns/loading/progress-bar). |
| 1224 |
|
| 1225 |
#### Request Indicators |
| 1226 |
|
| 1227 |
When an AJAX request is issued it is often good to let the user know that something is happening since the browser |
| 1228 |
will not give them any feedback. You can accomplish this in htmx by using `htmx-indicator` class. |
| 1229 |
|
| 1230 |
The `htmx-indicator` class is defined so that the opacity of any element with this class is `0` by default, making it |
| 1231 |
invisible but present in the DOM. |
| 1232 |
|
| 1233 |
When htmx issues a request, it will put a `htmx-request` class onto an element (either the requesting element or |
| 1234 |
another element, if specified). The `htmx-request` class will cause a child element with the `htmx-indicator` class |
| 1235 |
on it to transition to an opacity of `1`, showing the indicator. |
| 1236 |
|
| 1237 |
```html |
| 1238 |
<button hx-get="/click"> |
| 1239 |
Click Me! |
| 1240 |
<img class="htmx-indicator" src="/spinner.gif" alt="Loading..."> |
| 1241 |
</button> |
| 1242 |
``` |
| 1243 |
|
| 1244 |
Here we have a button. When it is clicked the `htmx-request` class will be added to it, which will reveal the spinner |
| 1245 |
gif element. |
| 1246 |
|
| 1247 |
The `htmx-indicator` class uses opacity to hide and show the progress indicator but if you would prefer another |
| 1248 |
mechanism you can create your own CSS transition like so: |
| 1249 |
|
| 1250 |
```css |
| 1251 |
.htmx-indicator { |
| 1252 |
display: none; |
| 1253 |
} |
| 1254 |
|
| 1255 |
.htmx-request .htmx-indicator { |
| 1256 |
display: inline; |
| 1257 |
} |
| 1258 |
|
| 1259 |
.htmx-request.htmx-indicator { |
| 1260 |
display: inline; |
| 1261 |
} |
| 1262 |
``` |
| 1263 |
|
| 1264 |
If you want the `htmx-request` class added to a different element, you can use |
| 1265 |
the [`hx-indicator`](/reference/attributes/hx-indicator) |
| 1266 |
attribute with a CSS selector to do so: |
| 1267 |
|
| 1268 |
```html |
| 1269 |
<div> |
| 1270 |
<button hx-get="/click" hx-indicator="#indicator"> |
| 1271 |
Click Me! |
| 1272 |
</button> |
| 1273 |
<img id="indicator" class="htmx-indicator" src="/spinner.gif" alt="Loading..."/> |
| 1274 |
</div> |
| 1275 |
``` |
| 1276 |
|
| 1277 |
Here we call out the indicator explicitly by id. |
| 1278 |
|
| 1279 |
Note that we could have placed the class on the parent `div` as well and had the same effect. |
| 1280 |
|
| 1281 |
You can also add the [`disabled` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/disabled) to |
| 1282 |
elements for the duration of a request by using the [`hx-disable`](/reference/attributes/hx-disable) attribute. |
| 1283 |
|
| 1284 |
### Targets |
| 1285 |
|
| 1286 |
By default, responses replace the element that made the request. |
| 1287 |
|
| 1288 |
Change this with [`hx-target`](/reference/attributes/hx-target). |
| 1289 |
|
| 1290 |
```html |
| 1291 |
<button hx-get="..." |
| 1292 |
hx-target="#results"> |
| 1293 |
Load Results |
| 1294 |
</button> |
| 1295 |
|
| 1296 |
<div id="results"> |
| 1297 |
<!-- Response goes here --> |
| 1298 |
</div> |
| 1299 |
``` |
| 1300 |
|
| 1301 |
The button makes the request. |
| 1302 |
|
| 1303 |
The response loads into `#results`. |
| 1304 |
|
| 1305 |
The button stays unchanged. |
| 1306 |
|
| 1307 |
#### Extended Selectors |
| 1308 |
Use [extended selectors](#extended-selectors-1) to target elements flexibly. |
| 1309 |
|
| 1310 |
Beyond standard CSS selectors, you can use: |
| 1311 |
|
| 1312 |
* [`this`](#this) - target the element itself |
| 1313 |
* [`closest <selector>`](#closest-selector) - find the nearest ancestor |
| 1314 |
* [`find <selector>`](#find-selector) - find the first child |
| 1315 |
* [`next`](#next) - target the next sibling |
| 1316 |
* [`next <selector>`](#next-selector) - find next sibling matching `<selector>` |
| 1317 |
* [`previous`](#previous) - target the previous sibling |
| 1318 |
* [`previous <selector>`](#previous-selector) - find previous sibling matching `<selector>` |
| 1319 |
* And more... |
| 1320 |
|
| 1321 |
See the full [extended selectors guide](#extended-selectors-1) for all options and examples. |
| 1322 |
|
| 1323 |
This keeps your HTML cleaner without requiring `id` attributes everywhere. |
| 1324 |
|
| 1325 |
### Swaps |
| 1326 |
|
| 1327 |
htmx offers many different ways to swap the HTML returned into the DOM. By default, the content replaces the |
| 1328 |
[innerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) of the target element, which is called |
| 1329 |
an `innerHTML` swap. |
| 1330 |
|
| 1331 |
This is similar to how the `target` attribute on links and forms works, placing the retrieved document within an iframe. |
| 1332 |
|
| 1333 |
You can modify this by using the [`hx-swap`](/reference/attributes/hx-swap) attribute with any of the following values: |
| 1334 |
|
| 1335 |
| Name | Description | |
| 1336 |
|-----------------------------|-------------------------------------------------------------------------------------------------------------------------------------------| |
| 1337 |
| `innerHTML` | the default, puts the content inside the target element | |
| 1338 |
| `outerHTML` | replaces the entire target element with the returned content | |
| 1339 |
| `beforebegin` (or `before`) | prepends the content before the target in the target's parent element | |
| 1340 |
| `afterbegin` (or `prepend`) | prepends the content before the first child inside the target | |
| 1341 |
| `beforeend` (or `append`) | appends the content after the last child inside the target | |
| 1342 |
| `afterend` (or `after`) | appends the content after the target in the target's parent element | |
| 1343 |
| `delete` | deletes the target element regardless of the response | |
| 1344 |
| `none` | does not append content from response ([Out of Band Swaps](#oob_swaps) and [Response Headers](#response-headers) will still be processed) | |
| 1345 |
| `innerMorph` | morphs the children of the target element, preserving as much of the existing DOM as possible | |
| 1346 |
| `outerMorph` | morphs the target element itself, preserving as much of the existing DOM as possible | |
| 1347 |
| `textContent` | Set the target's text content (no HTML parsing) | |
| 1348 |
|
| 1349 |
#### Morph Swaps |
| 1350 |
|
| 1351 |
htmx includes built-in `innerMorph` and `outerMorph` swaps that merge new content into the existing DOM rather than |
| 1352 |
simply replacing it. They often do a better job preserving things like focus, video state, etc. by mutating existing |
| 1353 |
nodes in-place during the swap operation, at the cost of more CPU. |
| 1354 |
|
| 1355 |
Consider this HTML: |
| 1356 |
|
| 1357 |
```html |
| 1358 |
<div id="video-elt"> |
| 1359 |
<h1>Title</h1> |
| 1360 |
<iframe id="video" width="791" height="445" src="https://www.youtube.com/embed/dQw4w9WgXcQ"></iframe> |
| 1361 |
</div> |
| 1362 |
<button hx-get="/swap" |
| 1363 |
hx-target="#video-elt" |
| 1364 |
hx-swap="outerMorph"> |
| 1365 |
Swap Header To Bottom |
| 1366 |
</button> |
| 1367 |
``` |
| 1368 |
|
| 1369 |
If the response content for this looks like this: |
| 1370 |
|
| 1371 |
```html |
| 1372 |
<div id="video-elt"> |
| 1373 |
<iframe id="video" width="791" height="445" src="https://www.youtube.com/embed/dQw4w9WgXcQ"></iframe> |
| 1374 |
<h1>Title</h1> |
| 1375 |
</div> |
| 1376 |
``` |
| 1377 |
|
| 1378 |
Then htmx will "morph" the existing content to the new structure. Note that the `h1` element has moved below the |
| 1379 |
video. With the `outerHTML` swap this will cause the video to stop playing and reset. However, the morphing algorithm |
| 1380 |
uses ID elements to intelligently mutate the DOM and preserve the existing video element, keeping the video playing |
| 1381 |
smoothly. |
| 1382 |
|
| 1383 |
Note that a similar effect can be achieved with the [`hx-preserve`](/reference/attributes/hx-preserve) attribute, discussed below. |
| 1384 |
|
| 1385 |
##### Excluding Elements from Morphing |
| 1386 |
|
| 1387 |
Add `hx-morph-skip` or `hx-morph-skip-children` to elements in your server templates: |
| 1388 |
|
| 1389 |
- `hx-morph-skip` - completely skip morphing specific elements (attrs + children stay frozen) |
| 1390 |
- `hx-morph-skip-children` - update element attributes but preserve children |
| 1391 |
|
| 1392 |
Or configure globally with CSS selectors: |
| 1393 |
|
| 1394 |
```javascript |
| 1395 |
htmx.config.morphSkip = 'custom-widget, .frozen'; |
| 1396 |
htmx.config.morphSkipChildren = 'lit-component, .sortable'; |
| 1397 |
``` |
| 1398 |
|
| 1399 |
Useful for third-party widgets, custom web components, or active animations. |
| 1400 |
|
| 1401 |
#### View Transitions |
| 1402 |
|
| 1403 |
The [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) |
| 1404 |
gives developers a way to create an animated transition between different DOM states. |
| 1405 |
|
| 1406 |
htmx supports view transitions via: |
| 1407 |
- Setting `htmx.config.transitions` to `true` globally |
| 1408 |
- Per-swap via `hx-swap` `transition` property: `hx-swap="outerHTML transition:true"` |
| 1409 |
- For boosted elements: [`hx-boost`](/reference/attributes/hx-boost)`="transition:true"` |
| 1410 |
|
| 1411 |
#### Swap Options |
| 1412 |
|
| 1413 |
The [`hx-swap`](/reference/attributes/hx-swap) attribute also supports options for tuning the swapping behavior of htmx. For |
| 1414 |
example, by default htmx will swap in the title of a title tag found anywhere in the new content. You can turn this |
| 1415 |
behavior off by setting the `ignoreTitle` modifier to true: |
| 1416 |
|
| 1417 |
```html |
| 1418 |
<button hx-post="/like" hx-swap="outerHTML ignoreTitle:true">Like</button> |
| 1419 |
``` |
| 1420 |
|
| 1421 |
The modifiers available on `hx-swap` are (parsed as [HCON](#hcon)): |
| 1422 |
|
| 1423 |
| Option | Description | |
| 1424 |
|--------------|------------------------------------------------------------------------------------------------------| |
| 1425 |
| swap | A time interval (e.g., 100ms, 1s) to delay the swap operation | |
| 1426 |
| transition | true or false, whether to use the view transition API for this swap | |
| 1427 |
| ignoreTitle | If set to true, any title found in the new content will be ignored and not update the document title | |
| 1428 |
| strip | true or false, whether to strip the outer element when swapping (unwrap the content) | |
| 1429 |
| focus-scroll | true or false, whether to scroll focused elements into view | |
| 1430 |
| swapEmpty | true or false, whether to perform the main swap when the response body is empty (`false` skips it). Defaults to [`htmx.config.defaultSwapEmpty`](/reference/config/htmx-config-defaultSwapEmpty) | |
| 1431 |
| scroll | top or bottom, will scroll the target element to its top or bottom | |
| 1432 |
| show | top or bottom, will scroll the target element's top or bottom into view | |
| 1433 |
| target | A selector to retarget the swap to a different element | |
| 1434 |
|
| 1435 |
All swap modifiers appear after the swap style is specified, and are colon-separated. |
| 1436 |
|
| 1437 |
See the [`hx-swap`](/reference/attributes/hx-swap) documentation for more details on these options. |
| 1438 |
|
| 1439 |
### Parameters |
| 1440 |
|
| 1441 |
By default, an element that causes a request will include its `value` if it has one. If the element is a form it |
| 1442 |
will include the values of all inputs within it. |
| 1443 |
|
| 1444 |
As with HTML forms, the `name` attribute of the input is used as the parameter name in the request that htmx sends. |
| 1445 |
|
| 1446 |
Additionally, if the element causes a non-`GET` request, the values of all the inputs of the associated form will be |
| 1447 |
included (typically this is the nearest enclosing form, but could be different if e.g. `<button form="associated-form">` |
| 1448 |
is used). |
| 1449 |
|
| 1450 |
If you wish to include the values of other elements, you can use the [`hx-include`](/reference/attributes/hx-include) attribute |
| 1451 |
with a CSS selector of all the elements whose values you want to include in the request. |
| 1452 |
|
| 1453 |
Finally, if you want to programmatically modify the parameters, you can use the [`htmx:config:request`](/reference/events/htmx-config-request) |
| 1454 |
event. |
| 1455 |
|
| 1456 |
#### File Upload |
| 1457 |
|
| 1458 |
If you wish to upload files via an htmx request, you can set the [`hx-encoding`](/reference/attributes/hx-encoding) attribute to |
| 1459 |
`multipart/form-data`. This will use a `FormData` object to submit the request, which will properly include the file |
| 1460 |
in the request. |
| 1461 |
|
| 1462 |
Note that depending on your server-side technology, you may have to handle requests with this type of body content very |
| 1463 |
differently. |
| 1464 |
|
| 1465 |
## Requests & Responses |
| 1466 |
Htmx expects responses to the AJAX requests it makes to be HTML, typically HTML fragments (although a full HTML |
| 1467 |
document, matched with a [`hx-select`](/reference/attributes/hx-select) tag can be useful too). |
| 1468 |
|
| 1469 |
Htmx will then swap the returned HTML into the document at the target specified and with the swap strategy specified. |
| 1470 |
|
| 1471 |
Sometimes you might want to do nothing in the swap, but still perhaps trigger a client side |
| 1472 |
event ([see below](#response-headers)). |
| 1473 |
|
| 1474 |
For this situation, by default, you can return a `204 - No Content` response code, and htmx will ignore the content of |
| 1475 |
the response. |
| 1476 |
|
| 1477 |
In the event of a connection error, the [`htmx:error`](/reference/events/htmx-error) event will be triggered. |
| 1478 |
|
| 1479 |
#### Configuring Response Handling |
| 1480 |
|
| 1481 |
By default, htmx will swap content for all HTTP responses except `204` and `304` status codes. This includes error |
| 1482 |
responses (4xx, 5xx). You can customize this behavior using the [`hx-status`](/reference/attributes/hx-status) attribute pattern (`hx-status:XXX`) or by configuring |
| 1483 |
`htmx.config.noSwap`. |
| 1484 |
|
| 1485 |
##### Status-Code Conditional Swapping |
| 1486 |
|
| 1487 |
The `hx-status:XXX` attribute allows you to specify different swap behaviors based on the HTTP status code of the |
| 1488 |
response. |
| 1489 |
This gives you fine-grained control over how different response statuses are handled. |
| 1490 |
|
| 1491 |
```html |
| 1492 |
<button hx-get="/data" |
| 1493 |
hx-status:404="none" |
| 1494 |
hx-status:500="target:#error-container"> |
| 1495 |
Load Data |
| 1496 |
</button> |
| 1497 |
``` |
| 1498 |
|
| 1499 |
```html |
| 1500 |
<form hx-post="/submit" |
| 1501 |
hx-target="#result" |
| 1502 |
hx-status:422="target:#validation-errors" |
| 1503 |
hx-status:500="target:#server-error" |
| 1504 |
hx-status:503="none"> |
| 1505 |
<input name="email"> |
| 1506 |
<button type="submit">Submit</button> |
| 1507 |
</form> |
| 1508 |
|
| 1509 |
<div id="result"></div> |
| 1510 |
<div id="validation-errors"></div> |
| 1511 |
<div id="server-error"></div> |
| 1512 |
``` |
| 1513 |
|
| 1514 |
In this example: |
| 1515 |
|
| 1516 |
- Successful responses (2xx) swap into `#result` (default behavior) |
| 1517 |
- `422` responses swap into `#validation-errors` |
| 1518 |
- `500` responses swap into `#server-error` |
| 1519 |
- `503` responses don't swap at all |
| 1520 |
|
| 1521 |
#### Request Headers |
| 1522 |
|
| 1523 |
htmx includes headers in the requests it makes: |
| 1524 |
|
| 1525 |
| Header | Description | |
| 1526 |
|------------------------------|------------------------------------------------------------------------------------------------------| |
| 1527 |
| [`HX-Boosted`](/reference/headers/HX-Boosted) | indicates that the request is via an element using [`hx-boost`](/reference/attributes/hx-boost) | |
| 1528 |
| [`HX-Current-URL`](/reference/headers/HX-Current-URL) | the current URL of the browser | |
| 1529 |
| [`HX-Request`](/reference/headers/HX-Request) | always "true" | |
| 1530 |
| [`HX-Request-Type`](/reference/headers/HX-Request-Type) | `"partial"` for targeted swaps, `"full"` for body-level or `hx-select` requests | |
| 1531 |
| [`HX-Source`](/reference/headers/HX-Source) | the source element in `tag#id` format (e.g. `button#submit`) | |
| 1532 |
| [`HX-Target`](/reference/headers/HX-Target) | the target element in `tag#id` format (e.g. `div#results`) | |
| 1533 |
|
| 1534 |
#### Response Headers |
| 1535 |
|
| 1536 |
htmx supports htmx-specific response headers: |
| 1537 |
|
| 1538 |
| Header | Description | |
| 1539 |
|--------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |
| 1540 |
| [`HX-Location`](/reference/headers/HX-Location) | allows you to do a client-side redirect that does not do a full page reload | |
| 1541 |
| [`HX-Push-Url`](/reference/headers/HX-Push-Url) | pushes a new url into the history stack | |
| 1542 |
| [`HX-Redirect`](/reference/headers/HX-Redirect) | can be used to do a client-side redirect to a new location | |
| 1543 |
| [`HX-Refresh`](/reference/headers/HX-Refresh) | if set to "true" the client-side will do a full refresh of the page | |
| 1544 |
| [`HX-Replace-Url`](/reference/headers/HX-Replace-Url) | replaces the current URL in the location bar | |
| 1545 |
| [`HX-Reswap`](/reference/headers/HX-Reswap) | allows you to specify how the response will be swapped. See [`hx-swap`](/reference/attributes/hx-swap) for possible values | |
| 1546 |
| [`HX-Retarget`](/reference/headers/HX-Retarget) | a CSS selector that updates the target of the content update to a different element on the page | |
| 1547 |
| [`HX-Reselect`](/reference/headers/HX-Reselect) | a CSS selector that allows you to choose which part of the response is used to be swapped in. Overrides an existing [`hx-select`](/reference/attributes/hx-select) on the triggering element | |
| 1548 |
| [`HX-Trigger`](/reference/headers/HX-Trigger) | allows you to trigger client-side events | |
| 1549 |
|
| 1550 |
For more on the `HX-Trigger` headers, see [`HX-Trigger` Response Headers](/reference/headers/HX-Trigger). |
| 1551 |
|
| 1552 |
Submitting a form via htmx has the benefit of no longer needing |
| 1553 |
the [Post/Redirect/Get Pattern](https://en.wikipedia.org/wiki/Post/Redirect/Get). |
| 1554 |
After successfully processing a POST request on the server, you don't need to return |
| 1555 |
a [HTTP 302 (Redirect)](https://en.wikipedia.org/wiki/HTTP_302). You can directly return the new HTML fragment. |
| 1556 |
|
| 1557 |
Also, the response headers above are not provided to htmx for processing with 3xx Redirect response codes |
| 1558 |
like [HTTP 302 (Redirect)](https://en.wikipedia.org/wiki/HTTP_302). Instead, the browser will intercept the redirection |
| 1559 |
internally and return the headers and response from the redirected URL. Where possible use alternative response codes |
| 1560 |
like `200` to allow returning of these response headers. |
| 1561 |
|
| 1562 |
## Client-Side Scripting |
| 1563 |
<details class="warning"> |
| 1564 |
<summary>Changes in htmx 4.0</summary> |
| 1565 |
|
| 1566 |
htmx 4.0 changed event names significantly when compared with htmx 2.0, making them much more standardized. |
| 1567 |
|
| 1568 |
See the full event mapping in the [Changes in htmx 4.0](#migration) document. |
| 1569 |
|
| 1570 |
**Note:** All events now provide a consistent `ctx` object with request/response information. |
| 1571 |
|
| 1572 |
</details> |
| 1573 |
|
| 1574 |
While htmx encourages a hypermedia approach to building web applications, it offers many options for client scripting. |
| 1575 |
Scripting is included in the REST-ful description of web architecture, |
| 1576 |
see: [Code-On-Demand](https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_7). As much as is |
| 1577 |
feasible, we recommend a [hypermedia-friendly](/essays/hypermedia-friendly-scripting) approach to scripting in your web |
| 1578 |
application: |
| 1579 |
|
| 1580 |
* [Respect HATEOAS](/essays/hypermedia-friendly-scripting#prime_directive) |
| 1581 |
* [Use events to communicate between components](/essays/hypermedia-friendly-scripting#events) |
| 1582 |
* [Use islands to isolate non-hypermedia components from the rest of your application](/essays/hypermedia-friendly-scripting#islands) |
| 1583 |
* [Consider inline scripting](/essays/hypermedia-friendly-scripting#inline) |
| 1584 |
|
| 1585 |
The primary integration point between htmx and scripting solutions is the events that htmx sends and can respond to. |
| 1586 |
|
| 1587 |
We have an entire chapter entitled ["Client-Side Scripting"](https://hypermedia.systems/client-side-scripting/) in [our |
| 1588 |
book](https://hypermedia.systems) that looks at how scripting can be integrated into your htmx-based application. |
| 1589 |
|
| 1590 |
### Events |
| 1591 |
|
| 1592 |
Htmx has an extensive events mechanism, which doubles as the logging system. |
| 1593 |
|
| 1594 |
If you want to register for a given htmx event you can use |
| 1595 |
|
| 1596 |
```javascript |
| 1597 |
document.body.addEventListener('htmx:after:init', function (evt) { |
| 1598 |
myJavascriptLib.init(evt.detail.elt); |
| 1599 |
}); |
| 1600 |
``` |
| 1601 |
|
| 1602 |
or, if you would prefer, you can use the following htmx helper: |
| 1603 |
|
| 1604 |
```javascript |
| 1605 |
htmx.on("htmx:after:init", function (evt) { |
| 1606 |
myJavascriptLib.init(evt.detail.elt); |
| 1607 |
}); |
| 1608 |
``` |
| 1609 |
|
| 1610 |
The `htmx:after:process` event is fired every time an element is processed by htmx, and is effectively the equivalent |
| 1611 |
to the normal `load` event. |
| 1612 |
|
| 1613 |
#### Initialize A 3rd Party Library With Events |
| 1614 |
|
| 1615 |
Using the `htmx:after:process` event to initialize content is so common that htmx provides a helper function: |
| 1616 |
|
| 1617 |
```javascript |
| 1618 |
htmx.onLoad(function (target) { |
| 1619 |
myJavascriptLib.init(target); |
| 1620 |
}); |
| 1621 |
``` |
| 1622 |
|
| 1623 |
This does the same thing as the first example, but is a little cleaner. |
| 1624 |
|
| 1625 |
#### Configure a Request With Events |
| 1626 |
|
| 1627 |
You can handle the [`htmx:config:request`](/reference/events/htmx-config-request) event in order to modify an AJAX request |
| 1628 |
before it is issued: |
| 1629 |
|
| 1630 |
```javascript |
| 1631 |
document.body.addEventListener('htmx:config:request', function (evt) { |
| 1632 |
evt.detail.ctx.request.parameters['auth_token'] = getAuthToken(); // add a new parameter into the request |
| 1633 |
evt.detail.ctx.request.headers['Authentication-Token'] = getAuthToken(); // add a new header into the request |
| 1634 |
}); |
| 1635 |
``` |
| 1636 |
|
| 1637 |
Here we add a parameter and header to the request before it is sent. |
| 1638 |
|
| 1639 |
### The `hx-on:*` Attributes |
| 1640 |
|
| 1641 |
HTML allows the embedding of inline scripts via the [ |
| 1642 |
`onevent` properties](https://developer.mozilla.org/en-US/docs/Web/Events/Event_handlers#using_onevent_properties), |
| 1643 |
such as `onClick`: |
| 1644 |
|
| 1645 |
```html |
| 1646 |
<button onclick="alert('You clicked me!')"> |
| 1647 |
Click Me! |
| 1648 |
</button> |
| 1649 |
``` |
| 1650 |
|
| 1651 |
This feature allows scripting logic to be co-located with the HTML elements the logic applies to, giving good |
| 1652 |
[Locality of Behaviour (LoB)](/essays/locality-of-behaviour). |
| 1653 |
|
| 1654 |
Unfortunately, HTML only allows `on*` attributes for a fixed |
| 1655 |
number of [specific DOM events](https://www.w3schools.com/tags/ref_eventattributes.asp) (e.g. `onclick`) and |
| 1656 |
doesn't provide a generalized mechanism for responding to arbitrary events on elements. |
| 1657 |
|
| 1658 |
In order to address this shortcoming, htmx offers [`hx-on:*`](/reference/attributes/hx-on) attributes. |
| 1659 |
|
| 1660 |
These attributes allow you to respond to any event in a manner that preserves the LoB of the standard `on*` properties, |
| 1661 |
and provide some nice quality of life improvements over the standard javascript API. |
| 1662 |
|
| 1663 |
If you want to respond to the `click` event using an `hx-on` attribute, we would write this: |
| 1664 |
|
| 1665 |
```html |
| 1666 |
<button hx-on:click="alert('You clicked me!')"> |
| 1667 |
Click Me! |
| 1668 |
</button> |
| 1669 |
``` |
| 1670 |
|
| 1671 |
So, the string `hx-on`, followed by a colon (or a dash), then by the name of the event. |
| 1672 |
|
| 1673 |
#### The Scripting API |
| 1674 |
|
| 1675 |
htmx provides some top level helper methods in `hx-on` handlers that make async scripting more enjoyable: |
| 1676 |
|
| 1677 |
| function | description | |
| 1678 |
|-------------|--------------------------------------------------------------------------------------------------------------------------------------| |
| 1679 |
| `find()` | allows you to find content relative to the current element (e.g. `find('next div')` will find the next div after the current element | |
| 1680 |
| `findAll()` | allows you to find multiple elements relative to the current element | |
| 1681 |
| `timeout()` | allows you to wait for a given amount of time (e.g. `await timeout(100)` before continuing | |
| 1682 |
|
| 1683 |
#### Scripting Examples |
| 1684 |
|
| 1685 |
Here is an example that adds a parameter to an htmx request |
| 1686 |
|
| 1687 |
```html |
| 1688 |
<button hx-post="/example" |
| 1689 |
hx-on:htmx:config:request="ctx.request.parameters.example = 'Hello Scripting!'"> |
| 1690 |
Post Me! |
| 1691 |
</button> |
| 1692 |
``` |
| 1693 |
|
| 1694 |
Here the `example` parameter is added to the `POST` request before it is issued, with the value 'Hello Scripting!'. |
| 1695 |
|
| 1696 |
Another use case is to [reset user input](/patterns/forms/reset-on-submit) on successful requests using the [`htmx:after:swap`](/reference/events/htmx-after-swap) |
| 1697 |
event: |
| 1698 |
|
| 1699 |
```html |
| 1700 |
<button hx-post="/example" |
| 1701 |
hx-on:htmx:after:request="find('closest form').reset()"> |
| 1702 |
Post Me! |
| 1703 |
</button> |
| 1704 |
``` |
| 1705 |
|
| 1706 |
### 3rd Party Javascript |
| 1707 |
|
| 1708 |
Htmx integrates well with third party libraries. |
| 1709 |
|
| 1710 |
If the library fires events on the DOM, you can use those events to trigger requests from htmx. |
| 1711 |
|
| 1712 |
A good example of this is the [SortableJS demo](/patterns/records/drag-to-reorder): |
| 1713 |
|
| 1714 |
```html |
| 1715 |
<form class="sortable" hx-post="/items" hx-trigger="end"> |
| 1716 |
<div class="htmx-indicator">Updating...</div> |
| 1717 |
<div><input type='hidden' name='item' value='1'/>Item 1</div> |
| 1718 |
<div><input type='hidden' name='item' value='2'/>Item 2</div> |
| 1719 |
<div><input type='hidden' name='item' value='2'/>Item 3</div> |
| 1720 |
</form> |
| 1721 |
``` |
| 1722 |
|
| 1723 |
With Sortable, as with most javascript libraries, you need to initialize content at some point. |
| 1724 |
|
| 1725 |
In htmx, the cleanest way to do this is using the `htmx.onLoad()` method to register a callback. |
| 1726 |
|
| 1727 |
This callback will be called whenever htmx inserts new content into the DOM, allowing you to initialize |
| 1728 |
any widgets in the new content. |
| 1729 |
|
| 1730 |
```js |
| 1731 |
htmx.onLoad((content) => { |
| 1732 |
var sortables = content.querySelectorAll(".sortable"); |
| 1733 |
for (var i = 0; i < sortables.length; i++) { |
| 1734 |
var sortable = sortables[i]; |
| 1735 |
new Sortable(sortable, { |
| 1736 |
animation: 150, |
| 1737 |
ghostClass: 'blue-background-class' |
| 1738 |
}); |
| 1739 |
} |
| 1740 |
}) |
| 1741 |
``` |
| 1742 |
|
| 1743 |
This will ensure that as new content is added to the DOM by htmx, sortable elements are properly initialized. |
| 1744 |
|
| 1745 |
### See Also |
| 1746 |
|
| 1747 |
- [`hx-on`](/reference/attributes/hx-on) (attribute) |
| 1748 |
- [Hypermedia-Friendly Scripting](/essays/hypermedia-friendly-scripting) (essay) |
| 1749 |
- [Locality of Behaviour](/essays/locality-of-behaviour) (essay) |
| 1750 |
|
| 1751 |
## Multi-Target Updates |
| 1752 |
|
| 1753 |
### The Problem |
| 1754 |
|
| 1755 |
htmx requests normally update one target element. Sometimes you need to update multiple parts of the page at once. |
| 1756 |
|
| 1757 |
For example: After submitting a form, you want to update both the form itself and a notification counter. |
| 1758 |
|
| 1759 |
### The Solution |
| 1760 |
|
| 1761 |
htmx provides two ways to update multiple targets from a single response: |
| 1762 |
|
| 1763 |
1. **Out-of-Band Swaps** - Match elements by their `id` attribute |
| 1764 |
2. **Partial Tags** - Explicitly specify where content goes |
| 1765 |
|
| 1766 |
Choose the method that fits your needs. |
| 1767 |
|
| 1768 |
### Out-of-Band Swaps |
| 1769 |
|
| 1770 |
Use out-of-band swaps when you want to match elements by their `id`. |
| 1771 |
|
| 1772 |
Add [`hx-swap-oob`](/reference/attributes/hx-swap-oob)`="true"` to any element in your response. htmx will find the element with the same `id` in your page and swap it. |
| 1773 |
|
| 1774 |
**Server response:** |
| 1775 |
|
| 1776 |
```html |
| 1777 |
<div id="message" hx-swap-oob="true"> |
| 1778 |
Form submitted successfully! |
| 1779 |
</div> |
| 1780 |
|
| 1781 |
<form id="my-form"> |
| 1782 |
<!-- Updated form content --> |
| 1783 |
</form> |
| 1784 |
``` |
| 1785 |
|
| 1786 |
**Result:** |
| 1787 |
- The `div#message` updates wherever it exists in your page |
| 1788 |
- The form updates in its normal target location |
| 1789 |
|
| 1790 |
#### Customize the Swap |
| 1791 |
|
| 1792 |
Specify a different swap style: |
| 1793 |
|
| 1794 |
```html |
| 1795 |
<div id="notifications" hx-swap-oob="beforeend"> |
| 1796 |
<span>New notification</span> |
| 1797 |
</div> |
| 1798 |
``` |
| 1799 |
|
| 1800 |
This appends the content to `div#notifications` instead of replacing it. |
| 1801 |
|
| 1802 |
#### Target a Different Element |
| 1803 |
|
| 1804 |
Override the `id` matching by specifying a custom target: |
| 1805 |
|
| 1806 |
```html |
| 1807 |
<div hx-swap-oob="innerHTML:#status"> |
| 1808 |
Processing... |
| 1809 |
</div> |
| 1810 |
``` |
| 1811 |
|
| 1812 |
This swaps the content into the element matching `#status`, regardless of the element's own `id`. |
| 1813 |
|
| 1814 |
#### When to Use Out-of-Band Swaps |
| 1815 |
|
| 1816 |
Use out-of-band swaps when: |
| 1817 |
- Elements have consistent, unique `id` attributes |
| 1818 |
- You want simple, ID-based updates |
| 1819 |
- You're updating notification areas, counters, or status indicators |
| 1820 |
|
| 1821 |
### Partials (`<hx-partial>`) |
| 1822 |
|
| 1823 |
Use partials when you need explicit control over targeting. |
| 1824 |
|
| 1825 |
Wrap content in `<hx-partial>` tags. Specify where it goes with [`hx-target`](/reference/attributes/hx-target). |
| 1826 |
|
| 1827 |
**Server response:** |
| 1828 |
|
| 1829 |
```html |
| 1830 |
<hx-partial hx-target="#messages" hx-swap="beforeend"> |
| 1831 |
<div class="message">New message content</div> |
| 1832 |
</hx-partial> |
| 1833 |
|
| 1834 |
<hx-partial hx-target="#notifications"> |
| 1835 |
<span class="badge">5</span> |
| 1836 |
</hx-partial> |
| 1837 |
|
| 1838 |
<form id="my-form"> |
| 1839 |
<!-- Main form content --> |
| 1840 |
</form> |
| 1841 |
``` |
| 1842 |
|
| 1843 |
**Result:** |
| 1844 |
- First partial's content appends to `#messages` |
| 1845 |
- Second partial's content replaces contents of `#notifications` |
| 1846 |
- Form updates in its normal target location |
| 1847 |
|
| 1848 |
#### Attributes |
| 1849 |
|
| 1850 |
Each `<hx-partial>` accepts: |
| 1851 |
|
| 1852 |
- [`hx-target`](/reference/attributes/hx-target) - CSS selector for where to place content |
| 1853 |
- `id` - Shorthand alternative to `hx-target`. Targets the element with that ID (e.g. `<hx-partial id="messages">` targets `#messages`) |
| 1854 |
- [`hx-swap`](/reference/attributes/hx-swap) - Optional. Swap style (defaults to `innerHTML`) |
| 1855 |
|
| 1856 |
Either `hx-target` or `id` is required. If both are present, `hx-target` takes precedence. |
| 1857 |
|
| 1858 |
<details> |
| 1859 |
<summary>Alternative syntax for template languages that strip unknown tags</summary> |
| 1860 |
You can use the equivalent <code><template></code> form: <code><template hx type="partial" hx-target="..." hx-swap="..."></code>. htmx converts <code><hx-partial></code> to this form internally. |
| 1861 |
</details> |
| 1862 |
|
| 1863 |
#### Empty Response Behaviour |
| 1864 |
|
| 1865 |
When a response contains only `<hx-partial>` elements and no main content, htmx will **not** perform the main swap. |
| 1866 |
This is the opposite default to [`hx-swap-oob`](/reference/attributes/hx-swap-oob): with partials, an |
| 1867 |
all-partial response signals intent — the server is explicitly routing multiple targeted updates and there is no main |
| 1868 |
content to swap. |
| 1869 |
|
| 1870 |
```html |
| 1871 |
<!-- Server returns only partials — main target is left untouched --> |
| 1872 |
<hx-partial hx-target="#notifications"> |
| 1873 |
<span class="badge">5</span> |
| 1874 |
</hx-partial> |
| 1875 |
<hx-partial hx-target="#messages" hx-swap="beforeend"> |
| 1876 |
<div class="message">New message</div> |
| 1877 |
</hx-partial> |
| 1878 |
``` |
| 1879 |
|
| 1880 |
If you also want the main target cleared, add `swapEmpty:true` to `hx-swap` on the triggering element: |
| 1881 |
|
| 1882 |
```html |
| 1883 |
<button hx-post="/submit" hx-swap="outerHTML swapEmpty:true">Submit</button> |
| 1884 |
``` |
| 1885 |
|
| 1886 |
Or set the global default via [`htmx.config.defaultSwapEmpty`](/reference/config/htmx-config-defaultSwapEmpty). |
| 1887 |
|
| 1888 |
#### When to Use Partials |
| 1889 |
|
| 1890 |
Use partials when: |
| 1891 |
- Elements don't have `id` attributes |
| 1892 |
- You need to target by class or other selectors |
| 1893 |
- You want explicit control over what goes where |
| 1894 |
- You're building more complex update patterns |
| 1895 |
|
| 1896 |
### Choosing Between Them |
| 1897 |
|
| 1898 |
Both methods work together. Use them in the same response if needed. |
| 1899 |
|
| 1900 |
**Use out-of-band swaps** for simple ID-based updates. |
| 1901 |
|
| 1902 |
**Use partial tags** for everything else. |
| 1903 |
|
| 1904 |
### Additional Features |
| 1905 |
|
| 1906 |
#### Select Specific Elements for OOB |
| 1907 |
|
| 1908 |
Use [`hx-select-oob`](/reference/attributes/hx-select-oob) on the triggering element to extract specific elements from the response for out-of-band swapping: |
| 1909 |
|
| 1910 |
```html |
| 1911 |
<button hx-post="/submit" |
| 1912 |
hx-target="#form" |
| 1913 |
hx-select-oob="#message, #counter"> |
| 1914 |
Submit |
| 1915 |
</button> |
| 1916 |
``` |
| 1917 |
|
| 1918 |
This pulls `#message` and `#counter` from the response and swaps them out-of-band, even if they don't have `hx-swap-oob` attributes. |
| 1919 |
|
| 1920 |
#### Preserve Content During Swaps |
| 1921 |
|
| 1922 |
Add [`hx-preserve`](/reference/attributes/hx-preserve)`="true"` to elements you want to keep across swaps: |
| 1923 |
|
| 1924 |
```html |
| 1925 |
<video id="my-video" hx-preserve="true"> |
| 1926 |
<source src="video.mp4"> |
| 1927 |
</video> |
| 1928 |
``` |
| 1929 |
|
| 1930 |
This keeps the video playing even when the parent container gets updated. |
| 1931 |
|
| 1932 |
## HCON |
| 1933 |
HCON (htmx Configuration Object Notation) is htmx's mini config language for structured HTML attributes. |
| 1934 |
|
| 1935 |
```html |
| 1936 |
<meta name="htmx-config" content="transitions defaultTimeout:5000 sse.reconnect:true"> |
| 1937 |
``` |
| 1938 |
|
| 1939 |
The equivalent JSON form works too: |
| 1940 |
|
| 1941 |
```html |
| 1942 |
<meta name="htmx-config" content='{"transitions":true,"defaultTimeout":5000,"sse":{"reconnect":true}}'> |
| 1943 |
``` |
| 1944 |
|
| 1945 |
HCON drops the outer braces and accepts flag-style booleans, dotted paths, flexible quoting, and space-separated pairs. |
| 1946 |
|
| 1947 |
You encounter HCON any time htmx reads a structured attribute: |
| 1948 |
|
| 1949 |
- `hx-swap` modifiers: `innerHTML swap:200ms settle:100ms` |
| 1950 |
- `hx-trigger` modifiers: `click delay:500ms throttle:1s` |
| 1951 |
- `hx-config`: `credentials:"include" timeout:5000` |
| 1952 |
- `hx-vals` / `hx-headers`: `token:"abc" retry:3` |
| 1953 |
- `<meta name="htmx-config">` |
| 1954 |
- `HX-Location` response header |
| 1955 |
|
| 1956 |
--- |
| 1957 |
|
| 1958 |
### Syntax |
| 1959 |
|
| 1960 |
#### Key-value pairs |
| 1961 |
|
| 1962 |
Pairs are separated by spaces or commas. Both are equivalent. |
| 1963 |
|
| 1964 |
``` |
| 1965 |
key:value key2:value2 |
| 1966 |
key:value, key2:value2 |
| 1967 |
``` |
| 1968 |
|
| 1969 |
#### Value types |
| 1970 |
|
| 1971 |
| Input | Parsed as | |
| 1972 |
|---|---| |
| 1973 |
| `true` / `false` | boolean | |
| 1974 |
| `42`, `0.5` | number | |
| 1975 |
| `"quoted string"` | string (double quotes) | |
| 1976 |
| `'quoted string'` | string (single quotes) | |
| 1977 |
| `bare-word` | string | |
| 1978 |
| *(no value)* | `true` | |
| 1979 |
|
| 1980 |
```html |
| 1981 |
<!-- booleans --> |
| 1982 |
<button hx-get="/api" hx-config="validate"> <!-- validate: true --> |
| 1983 |
<button hx-get="/api" hx-config="validate:false"> <!-- validate: false --> |
| 1984 |
|
| 1985 |
<!-- numbers --> |
| 1986 |
<button hx-get="/api" hx-config="timeout:5000"> |
| 1987 |
|
| 1988 |
<!-- strings, quotes needed when value contains spaces or special chars --> |
| 1989 |
<button hx-get="/api" hx-config='credentials:"include"'> |
| 1990 |
<button hx-get="/api" hx-config="mode:'cors'"> |
| 1991 |
``` |
| 1992 |
|
| 1993 |
#### Dot-notation for nested keys |
| 1994 |
|
| 1995 |
Use `.` to set nested object properties: |
| 1996 |
|
| 1997 |
```html |
| 1998 |
<meta name="htmx-config" content="sse.reconnect:true sse.reconnectDelay:1000"> |
| 1999 |
``` |
| 2000 |
|
| 2001 |
This produces `{ sse: { reconnect: true, reconnectDelay: 1000 } }`. |
| 2002 |
|
| 2003 |
#### JSON fallback |
| 2004 |
|
| 2005 |
Any value starting with `{` is parsed as JSON instead of HCON. This lets you compose config server-side and inject it directly: |
| 2006 |
|
| 2007 |
```html |
| 2008 |
<!-- server renders this --> |
| 2009 |
<meta name="htmx-config" content='{"defaultSwap":"outerHTML","transitions":true}'> |
| 2010 |
|
| 2011 |
<!-- or on an element --> |
| 2012 |
<button hx-get="/api" hx-config='{"credentials":"include","timeout":5000}'> |
| 2013 |
``` |
| 2014 |
|
| 2015 |
JSON and HCON are not mixed, the entire string is one or the other. |
| 2016 |
|
| 2017 |
#### Escaping commas and special characters |
| 2018 |
|
| 2019 |
Wrap values in quotes when they contain commas, spaces, or HCON delimiters. |
| 2020 |
|
| 2021 |
```html |
| 2022 |
<!-- comma ends the trigger spec --> |
| 2023 |
<input hx-trigger="keyup from:.a, .b"> |
| 2024 |
|
| 2025 |
<!-- quoted, comma is part of the value --> |
| 2026 |
<input hx-trigger='keyup from:".a, .b"'> |
| 2027 |
|
| 2028 |
<!-- space ends the bare value --> |
| 2029 |
<button hx-vals="message:hello world"> |
| 2030 |
|
| 2031 |
<!-- quoted, the whole phrase is the value --> |
| 2032 |
<button hx-vals='message:"hello world"'> |
| 2033 |
``` |
| 2034 |
|
| 2035 |
Use whichever quote style the HTML attribute is not using: |
| 2036 |
|
| 2037 |
```html |
| 2038 |
<input hx-trigger="keyup from:'.a, .b'"> |
| 2039 |
<input hx-trigger='keyup from:".a, .b"'> |
| 2040 |
``` |
| 2041 |
|
| 2042 |
--- |
| 2043 |
|
| 2044 |
### Where HCON is used |
| 2045 |
|
| 2046 |
#### `hx-swap` modifiers |
| 2047 |
|
| 2048 |
The swap style comes first (not HCON), then modifiers are parsed as HCON: |
| 2049 |
|
| 2050 |
```html |
| 2051 |
<div hx-get="/update" hx-swap="innerHTML swap:200ms settle:100ms scroll:top"> |
| 2052 |
<div hx-get="/update" hx-swap="outerHTML transition:true ignoreTitle:true"> |
| 2053 |
``` |
| 2054 |
|
| 2055 |
The full JSON form is also accepted. When using JSON, omitting `"style"` falls back to `config.defaultSwap` as expected; including it overrides the style: |
| 2056 |
|
| 2057 |
```html |
| 2058 |
<!-- modifiers only, style = config.defaultSwap --> |
| 2059 |
<div hx-swap='{"swap":"200ms","settle":"100ms"}'> |
| 2060 |
|
| 2061 |
<!-- explicit style --> |
| 2062 |
<div hx-swap='{"style":"outerHTML","swap":"200ms"}'> |
| 2063 |
``` |
| 2064 |
|
| 2065 |
Available swap modifiers: `swap`, `settle`, `scroll`, `show`, `scrollTarget`, `showTarget`, |
| 2066 |
`transition`, `strip`, `ignoreTitle`, `focusScroll`, `target`. |
| 2067 |
|
| 2068 |
#### `hx-trigger` modifiers |
| 2069 |
|
| 2070 |
The event name comes first, then modifiers: |
| 2071 |
|
| 2072 |
```html |
| 2073 |
<input hx-get="/search" hx-trigger="keyup delay:300ms"> |
| 2074 |
<button hx-post="/save" hx-trigger="click throttle:1s"> |
| 2075 |
<div hx-get="/poll" hx-trigger="every 2s"> |
| 2076 |
<form hx-post="/submit" hx-trigger="submit once"> |
| 2077 |
``` |
| 2078 |
|
| 2079 |
Available trigger modifiers: `delay`, `throttle`, `from`, `target`, `consume`, `changed`, `once`. |
| 2080 |
|
| 2081 |
#### `hx-config` |
| 2082 |
|
| 2083 |
Merges into the request context before the request is issued. Useful for per-element fetch options: |
| 2084 |
|
| 2085 |
```html |
| 2086 |
<button hx-get="/slow" hx-config="timeout:30000"> |
| 2087 |
<button hx-get="https://api.example.com/data" hx-config='credentials:"include" mode:"cors"'> |
| 2088 |
``` |
| 2089 |
|
| 2090 |
#### `<meta name="htmx-config">` |
| 2091 |
|
| 2092 |
Sets global `htmx.config` values. Accepts HCON or JSON: |
| 2093 |
|
| 2094 |
```html |
| 2095 |
<!-- HCON --> |
| 2096 |
<meta name="htmx-config" content="defaultSwap:outerHTML transitions:true"> |
| 2097 |
|
| 2098 |
<!-- JSON --> |
| 2099 |
<meta name="htmx-config" content='{"defaultSwap":"outerHTML","transitions":true}'> |
| 2100 |
|
| 2101 |
<!-- nested via dot notation --> |
| 2102 |
<meta name="htmx-config" content="sse.reconnect:true sse.reconnectMaxAttempts:5"> |
| 2103 |
``` |
| 2104 |
|
| 2105 |
#### `HX-Location` response header |
| 2106 |
|
| 2107 |
The server can return HCON or JSON in this header: |
| 2108 |
|
| 2109 |
``` |
| 2110 |
HX-Location: /new-page |
| 2111 |
HX-Location: path:"/new-page" push:"true" |
| 2112 |
HX-Location: {"path":"/new-page","push":"true"} |
| 2113 |
``` |
| 2114 |
|
| 2115 |
--- |
| 2116 |
|
| 2117 |
### Attribute inheritance and `:append` |
| 2118 |
|
| 2119 |
HCON itself is a parsing format. The `:append` composition feature lives one level up, in htmx's attribute inheritance system. When you use `:append` on an attribute name, htmx merges the child value with the inherited parent value by concatenating them (stripping `{}`): |
| 2120 |
|
| 2121 |
```html |
| 2122 |
<div hx-headers:inherited='{"X-Tenant": "acme"}'> |
| 2123 |
<button hx-get="/api" |
| 2124 |
hx-headers:append='{"X-Request-ID": "123"}'> |
| 2125 |
<!-- sends both headers --> |
| 2126 |
</button> |
| 2127 |
</div> |
| 2128 |
``` |
| 2129 |
|
| 2130 |
This works for any attribute that accepts HCON/JSON, including `hx-vals` and `hx-headers`. |
| 2131 |
|
| 2132 |
--- |
| 2133 |
|
| 2134 |
### Notes and limitations |
| 2135 |
|
| 2136 |
- **Use JSON literals for primitive types.** `count:42` becomes a number, `enabled:true` becomes a boolean, and `name:bob` stays a string. |
| 2137 |
- **Quote values for grouping, not type control.** Quotes preserve spaces, commas, and delimiters. Quoted numeric and boolean values still parse as numbers and booleans. |
| 2138 |
- **Write durations naturally.** `200ms`, `2s`, and `1m` stay strings in HCON; htmx converts them where durations are expected. |
| 2139 |
- **Quote dotted keys to keep them literal.** `"a.b":1` produces `{"a.b": 1}`. Bare `a.b:1` produces `{a: {b: 1}}`. |
| 2140 |
- **Quote spaces and commas.** HCON-aware comma splitting preserves commas inside `[...]`, `(...)`, `<.../>`, and quotes. |
| 2141 |
- **Use JSON for arrays.** HCON has no array literal syntax, so use JSON fallback, such as `{"items":[1,2,3]}`. |
| 2142 |
- **Use dot-notation for nested objects.** `a.b.c:value` works; `a:{b:{c:value}}` does not. |
| 2143 |
- **Use `js:` for expressions.** HCON values are literals, so write `hx-vals="js:{token: getToken()}"` for dynamic values. |
| 2144 |
- **Avoid prototype keys.** `__proto__`, `constructor`, and `prototype` are ignored. |
| 2145 |
- **Choose JSON or HCON.** A string starting with `{` is JSON; the two syntaxes cannot be mixed. |
| 2146 |
|
| 2147 |
### See also |
| 2148 |
|
| 2149 |
- [`hx-swap`](/reference/attributes/hx-swap) |
| 2150 |
- [`hx-trigger`](/reference/attributes/hx-trigger) |
| 2151 |
- [`hx-vals`](/reference/attributes/hx-vals) |
| 2152 |
- [`hx-config`](/reference/attributes/hx-config) |
| 2153 |
|
| 2154 |
<hr data-sidebar-group="Features" /> |
| 2155 |
|
| 2156 |
## CSS Transitions |
| 2157 |
|
| 2158 |
htmx makes it easy to |
| 2159 |
use [CSS Transitions](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions) without |
| 2160 |
javascript. Consider this HTML content: |
| 2161 |
|
| 2162 |
```html |
| 2163 |
<div id="div1">Original Content</div> |
| 2164 |
``` |
| 2165 |
|
| 2166 |
Imagine this content is replaced by htmx via an ajax request with this new content: |
| 2167 |
|
| 2168 |
```html |
| 2169 |
<div id="div1" class="red">New Content</div> |
| 2170 |
``` |
| 2171 |
|
| 2172 |
Note two things: |
| 2173 |
|
| 2174 |
* The div has the *same* id in the original and in the new content |
| 2175 |
* The `red` class has been added to the new content |
| 2176 |
|
| 2177 |
Given this situation, we can write a CSS transition from the old state to the new state: |
| 2178 |
|
| 2179 |
```css |
| 2180 |
.red { |
| 2181 |
color: red; |
| 2182 |
transition: all ease-in 1s; |
| 2183 |
} |
| 2184 |
``` |
| 2185 |
|
| 2186 |
When htmx swaps in this new content, it will do so in such a way that the CSS transition will apply to the new content, |
| 2187 |
giving you a nice, smooth transition to the new state. |
| 2188 |
|
| 2189 |
So, in summary, all you need to do to use CSS transitions for an element is keep its `id` stable across requests! |
| 2190 |
|
| 2191 |
## Synchronization |
| 2192 |
|
| 2193 |
Often you want to coordinate the requests between two elements. For example, you may want a request from one element |
| 2194 |
to supersede the request of another element, or to wait until the other element's request has finished. |
| 2195 |
|
| 2196 |
htmx offers a [`hx-sync`](/reference/attributes/hx-sync) attribute to help you accomplish this. |
| 2197 |
|
| 2198 |
Consider a race condition between a form submission and an individual input's validation request in this HTML: |
| 2199 |
|
| 2200 |
```html |
| 2201 |
<form hx-post="/store"> |
| 2202 |
<input id="title" name="title" type="text" |
| 2203 |
hx-post="/validate" |
| 2204 |
hx-trigger="change"> |
| 2205 |
<button type="submit">Submit</button> |
| 2206 |
</form> |
| 2207 |
``` |
| 2208 |
|
| 2209 |
Without using `hx-sync`, filling out the input and immediately submitting the form triggers two parallel requests to |
| 2210 |
`/validate` and `/store`. |
| 2211 |
|
| 2212 |
Using `hx-sync="closest form"` on the input and `hx-sync="this:replace"` on the form will watch for requests from the |
| 2213 |
form |
| 2214 |
and abort an input's in flight request: |
| 2215 |
|
| 2216 |
```html |
| 2217 |
<form hx-post="/store" hx-sync="this:replace"> |
| 2218 |
<input id="title" name="title" type="text" |
| 2219 |
hx-post="/validate" |
| 2220 |
hx-trigger="change" |
| 2221 |
hx-sync="closest form"> |
| 2222 |
<button type="submit">Submit</button> |
| 2223 |
</form> |
| 2224 |
``` |
| 2225 |
|
| 2226 |
This resolves the synchronization between the two elements in a declarative way. |
| 2227 |
|
| 2228 |
htmx also supports a programmatic way to cancel requests: you can send the [`htmx:abort`](/reference/events/htmx-abort) event to an element to |
| 2229 |
cancel any in-flight requests: |
| 2230 |
|
| 2231 |
```html |
| 2232 |
<button id="request-button" hx-post="/example"> |
| 2233 |
Issue Request |
| 2234 |
</button> |
| 2235 |
<button onclick="htmx.trigger('#request-button', 'htmx:abort')"> |
| 2236 |
Cancel Request |
| 2237 |
</button> |
| 2238 |
``` |
| 2239 |
|
| 2240 |
More examples and details can be found on the [`hx-sync` attribute page.](/reference/attributes/hx-sync) |
| 2241 |
|
| 2242 |
## Confirmations |
| 2243 |
|
| 2244 |
Often you will want to confirm an action before issuing a request. htmx supports the [`hx-confirm`](/reference/attributes/hx-confirm) |
| 2245 |
attribute, which allows you to confirm an action using a simple javascript dialog: |
| 2246 |
|
| 2247 |
```html |
| 2248 |
<button hx-delete="/account" hx-confirm="Are you sure you wish to delete your account?"> |
| 2249 |
Delete My Account |
| 2250 |
</button> |
| 2251 |
``` |
| 2252 |
|
| 2253 |
`hx-confirm` may also contain JavaScript by using the `js:` or `javascript:` prefix. In this case |
| 2254 |
the JavaScript will be evaluated and, if a promise is returned, it will wait until the promise |
| 2255 |
resolves with a `true` value to continue |
| 2256 |
|
| 2257 |
```html |
| 2258 |
|
| 2259 |
<script> |
| 2260 |
async function swalConfirm() { |
| 2261 |
let result = await Swal.fire({ |
| 2262 |
title: "Are you sure?", |
| 2263 |
text: "You won't be able to revert this!", |
| 2264 |
icon: "warning", |
| 2265 |
showCancelButton: true, |
| 2266 |
confirmButtonColor: "#3085d6", |
| 2267 |
cancelButtonColor: "#d33", |
| 2268 |
confirmButtonText: "Yes, delete it!" |
| 2269 |
}) |
| 2270 |
return result.isConfirmed |
| 2271 |
} |
| 2272 |
</script> |
| 2273 |
<button hx-delete="/account" hx-confirm="js:swalConfirm()"> |
| 2274 |
Delete My Account |
| 2275 |
</button> |
| 2276 |
``` |
| 2277 |
|
| 2278 |
## Boosting |
| 2279 |
|
| 2280 |
Htmx supports "boosting" regular HTML anchors and forms with the [`hx-boost`](/reference/attributes/hx-boost) attribute. This |
| 2281 |
attribute will convert all anchor tags and forms into AJAX requests that, by default, target the body of the page. |
| 2282 |
|
| 2283 |
Here is an example: |
| 2284 |
|
| 2285 |
```html |
| 2286 |
<div hx-boost:inherited="true"> |
| 2287 |
<a href="/blog">Blog</a> |
| 2288 |
<a href="/about">About</a> |
| 2289 |
<a href="/contact">Contact</a> |
| 2290 |
</div> |
| 2291 |
``` |
| 2292 |
|
| 2293 |
The anchor tags in this div will issue an AJAX `GET` request to `/blog` and swap the response into the `body` tag. |
| 2294 |
|
| 2295 |
Note that `hx-boost` is using the `inherited` modifier here. |
| 2296 |
|
| 2297 |
### Progressive Enhancement |
| 2298 |
|
| 2299 |
A nice feature of `hx-boost` is that it degrades gracefully if javascript is not enabled: the links and forms continue |
| 2300 |
to work, they simply don't use ajax requests. |
| 2301 |
|
| 2302 |
This is known as |
| 2303 |
[Progressive Enhancement](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement), and it allows |
| 2304 |
a wider audience to use your site's functionality. |
| 2305 |
|
| 2306 |
Other htmx patterns can be adapted to achieve progressive enhancement as well, but they will require more thought. |
| 2307 |
|
| 2308 |
Consider the [active search](/patterns/forms/active-search) example. As it is written, it will not degrade gracefully: |
| 2309 |
someone who does not have javascript enabled will not be able to use this feature. This is done for simplicity's sake, |
| 2310 |
to keep the example as brief as possible. |
| 2311 |
|
| 2312 |
However, you could wrap the htmx-enhanced input in a form element: |
| 2313 |
|
| 2314 |
```html |
| 2315 |
<form action="/search" method="POST"> |
| 2316 |
<input class="form-control" type="search" |
| 2317 |
name="search" placeholder="Begin typing to search users..." |
| 2318 |
hx-post="/search" |
| 2319 |
hx-trigger="keyup changed delay:500ms, search" |
| 2320 |
hx-target="#search-results" |
| 2321 |
hx-indicator=".htmx-indicator"> |
| 2322 |
</form> |
| 2323 |
``` |
| 2324 |
|
| 2325 |
With this in place, javascript-enabled clients would still get the nice active-search UX, but non-javascript enabled |
| 2326 |
clients would be able to hit the enter key and still search. Even better, you could add a "Search" button as well. |
| 2327 |
You would then need to update the form with an [`hx-post`](/reference/attributes/hx-post) that mirrored the `action` attribute, or perhaps use `hx-boost` |
| 2328 |
on it. |
| 2329 |
|
| 2330 |
You would need to check on the server side for the [`HX-Request`](/reference/headers/HX-Request) header to differentiate between an htmx-driven and a |
| 2331 |
regular request, to determine exactly what to render to the client. |
| 2332 |
|
| 2333 |
Other patterns can be adapted similarly to achieve the progressive enhancement needs of your application. |
| 2334 |
|
| 2335 |
As you can see, this requires more thought and more work. It also rules some functionality entirely out of bounds. |
| 2336 |
These tradeoffs must be made by you, the developer, with respect to your projects goals and audience. |
| 2337 |
|
| 2338 |
[Accessibility](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/What_is_accessibility) is a concept |
| 2339 |
closely related to progressive enhancement. Using progressive enhancement techniques such as `hx-boost` will make your |
| 2340 |
htmx application more accessible to a wide array of users. |
| 2341 |
|
| 2342 |
htmx-based applications are very similar to normal, non-AJAX driven web applications because htmx is HTML-oriented. |
| 2343 |
|
| 2344 |
As such, the normal HTML accessibility recommendations apply. For example: |
| 2345 |
|
| 2346 |
* Use semantic HTML as much as possible (i.e. the right tags for the right things) |
| 2347 |
* Ensure focus state is clearly visible |
| 2348 |
* Associate text labels with all form fields |
| 2349 |
* Maximize the readability of your application with appropriate fonts, contrast, etc. |
| 2350 |
|
| 2351 |
## History |
| 2352 |
|
| 2353 |
<details class="warning"> |
| 2354 |
<summary>Changes in htmx 4.0</summary> |
| 2355 |
|
| 2356 |
History support in htmx 4.0 has changed significantly. We no longer snapshot the DOM and keep a copy in sessionStorage. |
| 2357 |
|
| 2358 |
Instead, we issue a full page request every time someone navigates to a history element. This is much less error-prone |
| 2359 |
and foolproof. It also eliminates security concerns regarding keeping history state in accessible storage |
| 2360 |
|
| 2361 |
This change makes history restoration much more reliable and reduces client-side complexity. |
| 2362 |
|
| 2363 |
</details> |
| 2364 |
|
| 2365 |
Htmx provides a simple mechanism for interacting with |
| 2366 |
the [browser history API](https://developer.mozilla.org/en-US/docs/Web/API/History_API): |
| 2367 |
|
| 2368 |
If you want a given element to push its request URL into the browser navigation bar and add the current state of the |
| 2369 |
page |
| 2370 |
to the browser's history, include the [`hx-push-url`](/reference/attributes/hx-push-url) attribute: |
| 2371 |
|
| 2372 |
```html |
| 2373 |
<a hx-get="/blog" hx-push-url="true">Blog</a> |
| 2374 |
``` |
| 2375 |
|
| 2376 |
When a user clicks on this link, htmx will push a new location onto the history stack. |
| 2377 |
|
| 2378 |
When a user hits the back button, htmx will retrieve the old content from the original URL and swap it back into the |
| 2379 |
body, |
| 2380 |
simulating "going back" to the previous state. |
| 2381 |
|
| 2382 |
**NOTE:** If you push a URL into the history, you **must** be able to navigate to that URL and get a full page back! |
| 2383 |
A user could copy and paste the URL into an email, or new tab. |
| 2384 |
|
| 2385 |
## Validation |
| 2386 |
|
| 2387 |
Htmx integrates with the [HTML5 Validation API](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation) |
| 2388 |
and will not issue a request for a form if a validatable input is invalid. |
| 2389 |
|
| 2390 |
Non-form elements do not validate before they make requests by default, but you can enable validation by setting |
| 2391 |
the [`hx-validate`](/reference/attributes/hx-validate) attribute to "true". |
| 2392 |
|
| 2393 |
## Web Components |
| 2394 |
|
| 2395 |
htmx doesn't automatically scan inside web components' shadow DOM. You must manually initialize it. |
| 2396 |
|
| 2397 |
After creating your shadow DOM, call [`htmx.process`](/reference/methods/htmx-process): |
| 2398 |
|
| 2399 |
```javascript |
| 2400 |
customElements.define('my-counter', class extends HTMLElement { |
| 2401 |
connectedCallback() { |
| 2402 |
const shadow = this.attachShadow({mode: 'open'}) |
| 2403 |
shadow.innerHTML = ` |
| 2404 |
<button hx-post="/increment" hx-target="#count">+1</button> |
| 2405 |
<div id="count">0</div> |
| 2406 |
` |
| 2407 |
htmx.process(shadow) // Initialize htmx for this shadow DOM |
| 2408 |
} |
| 2409 |
}) |
| 2410 |
|
| 2411 |
``` |
| 2412 |
|
| 2413 |
#### Targeting Elements Outside Shadow DOM |
| 2414 |
|
| 2415 |
Selectors like [`hx-target`](/reference/attributes/hx-target) only see elements inside the same shadow DOM. |
| 2416 |
|
| 2417 |
To break out: |
| 2418 |
|
| 2419 |
1. Target the host element, using `host`: |
| 2420 |
|
| 2421 |
```html |
| 2422 |
<button hx-get="..." hx-target="host"> |
| 2423 |
... |
| 2424 |
</button> |
| 2425 |
``` |
| 2426 |
|
| 2427 |
2. Target elements in main document, using `global:<selector>`: |
| 2428 |
|
| 2429 |
```html |
| 2430 |
<button hx-get="..." hx-target="global:#target"> |
| 2431 |
... |
| 2432 |
</button> |
| 2433 |
``` |
| 2434 |
|
| 2435 |
#### Components Without Shadow DOM |
| 2436 |
|
| 2437 |
Still call [`htmx.process`](/reference/methods/htmx-process) on the component: |
| 2438 |
|
| 2439 |
```javascript |
| 2440 |
customElements.define('simple-widget', class extends HTMLElement { |
| 2441 |
connectedCallback() { |
| 2442 |
this.innerHTML = `Load` |
| 2443 |
htmx.process(this) |
| 2444 |
} |
| 2445 |
}) |
| 2446 |
``` |
| 2447 |
|
| 2448 |
## Attribute Inheritance |
| 2449 |
|
| 2450 |
<details class="warning"> |
| 2451 |
<summary>Changes in htmx 4.0</summary> |
| 2452 |
|
| 2453 |
In htmx 2.0 attribute inheritance was implicit by default: elements inherited the attributes on their parents, such |
| 2454 |
as [`hx-target`](/reference/attributes/hx-target). In htmx 4.0 attribute inheritance is now explicit by default, using the `:inherited` modifier. |
| 2455 |
|
| 2456 |
</details> |
| 2457 |
|
| 2458 |
Inheritance allows you to "hoist" attributes up the DOM to avoid code duplication. |
| 2459 |
|
| 2460 |
Consider the following htmx: |
| 2461 |
|
| 2462 |
```html |
| 2463 |
<button hx-delete="/account" hx-confirm="Are you sure?"> |
| 2464 |
Delete My Account |
| 2465 |
</button> |
| 2466 |
<button hx-put="/account" hx-confirm="Are you sure?"> |
| 2467 |
Update My Account |
| 2468 |
</button> |
| 2469 |
``` |
| 2470 |
|
| 2471 |
Here we have a duplicate [`hx-confirm`](/reference/attributes/hx-confirm) attribute. |
| 2472 |
|
| 2473 |
We can hoist this attribute to a parent element using the `:inherited` modifier: |
| 2474 |
|
| 2475 |
```html |
| 2476 |
<div hx-confirm:inherited="Are you sure?"> |
| 2477 |
<button hx-delete="/account"> |
| 2478 |
Delete My Account |
| 2479 |
</button> |
| 2480 |
<button hx-put="/account"> |
| 2481 |
Update My Account |
| 2482 |
</button> |
| 2483 |
</div> |
| 2484 |
``` |
| 2485 |
|
| 2486 |
This `hx-confirm` attribute will now apply to all htmx-powered elements within it. |
| 2487 |
|
| 2488 |
## Extended Selectors |
| 2489 |
Extended selectors let you target elements in flexible ways. |
| 2490 |
|
| 2491 |
Use them with [`hx-target`](/reference/attributes/hx-target), [`hx-sync`](/reference/attributes/hx-sync), and other attributes that accept selectors. |
| 2492 |
|
| 2493 |
### Standard CSS Selectors |
| 2494 |
|
| 2495 |
Start with any CSS selector. |
| 2496 |
|
| 2497 |
```html |
| 2498 |
<!-- Target by ID --> |
| 2499 |
<button hx-get="/data" hx-target="#results">Load</button> |
| 2500 |
|
| 2501 |
<!-- Target by class --> |
| 2502 |
<button hx-get="/data" hx-target=".container">Load</button> |
| 2503 |
|
| 2504 |
<!-- Target by attribute --> |
| 2505 |
<button hx-get="/data" hx-target="[data-results]">Load</button> |
| 2506 |
``` |
| 2507 |
|
| 2508 |
### `this` |
| 2509 |
|
| 2510 |
Target the element itself. |
| 2511 |
|
| 2512 |
```html |
| 2513 |
<!-- Update the button when clicked --> |
| 2514 |
<button hx-get="/status" hx-target="this">Check Status</button> |
| 2515 |
``` |
| 2516 |
|
| 2517 |
The button will replace itself with the response. |
| 2518 |
|
| 2519 |
### `closest <selector>` |
| 2520 |
|
| 2521 |
Find the nearest ancestor matching the selector. |
| 2522 |
|
| 2523 |
Searches upward through parent elements. |
| 2524 |
|
| 2525 |
```html |
| 2526 |
<div class="card"> |
| 2527 |
<div class="card-body"> |
| 2528 |
<button hx-get="/refresh" hx-target="closest .card">Refresh</button> |
| 2529 |
</div> |
| 2530 |
</div> |
| 2531 |
``` |
| 2532 |
|
| 2533 |
The button targets its parent `.card` element. |
| 2534 |
|
| 2535 |
Works like [Element.closest()](https://developer.mozilla.org/docs/Web/API/Element/closest). |
| 2536 |
|
| 2537 |
### `find <selector>` |
| 2538 |
|
| 2539 |
Find the first child matching the selector. |
| 2540 |
|
| 2541 |
Searches downward through descendant elements. |
| 2542 |
|
| 2543 |
```html |
| 2544 |
<div hx-get="/user" hx-target="find .username"> |
| 2545 |
<span class="username">Loading...</span> |
| 2546 |
</div> |
| 2547 |
``` |
| 2548 |
|
| 2549 |
The div targets its child `.username` element. |
| 2550 |
|
| 2551 |
Works like [Element.querySelector()](https://developer.mozilla.org/docs/Web/API/Element/querySelector). |
| 2552 |
|
| 2553 |
### `findAll <selector>` |
| 2554 |
|
| 2555 |
Find all children matching the selector. |
| 2556 |
|
| 2557 |
```html |
| 2558 |
<div hx-get="/items" hx-target="findAll .item"> |
| 2559 |
<div class="item">Item 1</div> |
| 2560 |
<div class="item">Item 2</div> |
| 2561 |
</div> |
| 2562 |
``` |
| 2563 |
|
| 2564 |
Targets all `.item` elements inside the div. |
| 2565 |
|
| 2566 |
Works like [Element.querySelectorAll()](https://developer.mozilla.org/docs/Web/API/Element/querySelectorAll). |
| 2567 |
|
| 2568 |
### `next` |
| 2569 |
|
| 2570 |
Target the next sibling element. |
| 2571 |
|
| 2572 |
```html |
| 2573 |
<button hx-get="/more" hx-target="next">Load More</button> |
| 2574 |
<div>Content loads here</div> |
| 2575 |
``` |
| 2576 |
|
| 2577 |
Targets the element immediately after the button. |
| 2578 |
|
| 2579 |
Works like [`Element.nextElementSibling`](https://developer.mozilla.org/docs/Web/API/Element/nextElementSibling). |
| 2580 |
|
| 2581 |
### `next <selector>` |
| 2582 |
|
| 2583 |
Scan forward for the first matching element. |
| 2584 |
|
| 2585 |
Searches through all following siblings. |
| 2586 |
|
| 2587 |
```html |
| 2588 |
<button hx-get="/data" hx-target="next .results">Load</button> |
| 2589 |
<div class="other">Not here</div> |
| 2590 |
<div class="results">Loads here</div> |
| 2591 |
``` |
| 2592 |
|
| 2593 |
Skips siblings until it finds `.results`. |
| 2594 |
|
| 2595 |
### `previous` |
| 2596 |
|
| 2597 |
Target the previous sibling element. |
| 2598 |
|
| 2599 |
```html |
| 2600 |
<div>Content loads here</div> |
| 2601 |
<button hx-get="/more" hx-target="previous">Load More</button> |
| 2602 |
``` |
| 2603 |
|
| 2604 |
Targets the element immediately before the button. |
| 2605 |
|
| 2606 |
Works like [Element.previousElementSibling](https://developer.mozilla.org/docs/Web/API/Element/previousElementSibling). |
| 2607 |
|
| 2608 |
### `previous <selector>` |
| 2609 |
|
| 2610 |
Scan backward for the first matching element. |
| 2611 |
|
| 2612 |
Searches through all preceding siblings. |
| 2613 |
|
| 2614 |
```html |
| 2615 |
<div class="results">Loads here</div> |
| 2616 |
<div class="other">Not here</div> |
| 2617 |
<button hx-get="/data" hx-target="previous .results">Load</button> |
| 2618 |
``` |
| 2619 |
|
| 2620 |
Skips siblings until it finds `.results`. |
| 2621 |
|
| 2622 |
### Special Keywords |
| 2623 |
|
| 2624 |
#### `body` |
| 2625 |
|
| 2626 |
Target the document body. |
| 2627 |
|
| 2628 |
```html |
| 2629 |
<button hx-get="/page" hx-target="body">Load Page</button> |
| 2630 |
``` |
| 2631 |
|
| 2632 |
Useful for full-page updates. |
| 2633 |
|
| 2634 |
#### `document` |
| 2635 |
|
| 2636 |
Reference the entire document. |
| 2637 |
|
| 2638 |
```html |
| 2639 |
<div hx-trigger="click from:document">...</div> |
| 2640 |
``` |
| 2641 |
|
| 2642 |
Used primarily with event triggers. |
| 2643 |
|
| 2644 |
#### `window` |
| 2645 |
|
| 2646 |
Reference the window object. |
| 2647 |
|
| 2648 |
```html |
| 2649 |
<div hx-trigger="scroll from:window">...</div> |
| 2650 |
``` |
| 2651 |
|
| 2652 |
Used primarily with window events. |
| 2653 |
|
| 2654 |
#### `host` |
| 2655 |
|
| 2656 |
Target the shadow DOM host element. |
| 2657 |
|
| 2658 |
```html |
| 2659 |
<!-- Inside shadow DOM --> |
| 2660 |
<button hx-get="/data" hx-target="host">Update Host</button> |
| 2661 |
``` |
| 2662 |
|
| 2663 |
Only works inside shadow DOM. |
| 2664 |
|
| 2665 |
### `global <selector>` |
| 2666 |
|
| 2667 |
Search the entire document tree. |
| 2668 |
|
| 2669 |
By default, selectors search within the current shadow DOM boundary. |
| 2670 |
|
| 2671 |
```html |
| 2672 |
<!-- Inside shadow DOM --> |
| 2673 |
<button hx-get="/data" hx-target="global #results">Load</button> |
| 2674 |
|
| 2675 |
<!-- Targets #results in the main document --> |
| 2676 |
<div id="results"></div> |
| 2677 |
``` |
| 2678 |
|
| 2679 |
Crosses shadow DOM boundaries. |
| 2680 |
|
| 2681 |
### Multiple Targets |
| 2682 |
|
| 2683 |
`hx-target` only resolves to a single element. To swap the same response into multiple elements, use the [`hx-targets`](/extensions/hx-targets) extension attribute: |
| 2684 |
|
| 2685 |
```html |
| 2686 |
<script src="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/ext/hx-targets.js"></script> |
| 2687 |
|
| 2688 |
<button hx-get="/data" hx-targets="#results, #cache">Load</button> |
| 2689 |
``` |
| 2690 |
|
| 2691 |
See the [hx-targets extension docs](/extensions/hx-targets) for full details. |
| 2692 |
|
| 2693 |
### Hyperscript-Style Syntax |
| 2694 |
|
| 2695 |
Wrap selectors in `<.../>` for hyperscript compatibility. |
| 2696 |
|
| 2697 |
```html |
| 2698 |
<button hx-get="/data" hx-target="<#results/>">Load</button> |
| 2699 |
``` |
| 2700 |
|
| 2701 |
This mimics [hyperscript query literals](https://hyperscript.org/expressions/query-reference/). |
| 2702 |
|
| 2703 |
Useful if you're using hyperscript alongside htmx. |
| 2704 |
|
| 2705 |
### Common Patterns |
| 2706 |
|
| 2707 |
#### Update parent card |
| 2708 |
|
| 2709 |
```html |
| 2710 |
<div class="card"> |
| 2711 |
<button hx-delete="/item/1" hx-target="closest .card">Delete</button> |
| 2712 |
</div> |
| 2713 |
``` |
| 2714 |
|
| 2715 |
#### Update sibling container |
| 2716 |
|
| 2717 |
```html |
| 2718 |
<button hx-get="/data" hx-target="next .results">Load</button> |
| 2719 |
<div class="results"></div> |
| 2720 |
``` |
| 2721 |
|
| 2722 |
#### Update self |
| 2723 |
|
| 2724 |
```html |
| 2725 |
<div hx-get="/refresh" hx-target="this">Click to refresh</div> |
| 2726 |
``` |
| 2727 |
|
| 2728 |
#### Update child element |
| 2729 |
|
| 2730 |
```html |
| 2731 |
<div hx-get="/user" hx-target="find .username"> |
| 2732 |
<span class="username">Loading...</span> |
| 2733 |
</div> |
| 2734 |
``` |
| 2735 |
|
| 2736 |
### Notes |
| 2737 |
|
| 2738 |
* Selectors are evaluated once when htmx processes the element. They are not re-evaluated when the page changes. |
| 2739 |
|
| 2740 |
### Tips |
| 2741 |
|
| 2742 |
Start with simple CSS selectors. |
| 2743 |
|
| 2744 |
Use `this` for self-updates. |
| 2745 |
|
| 2746 |
Use `closest` to update parent containers. |
| 2747 |
|
| 2748 |
Use `find` to update child elements. |
| 2749 |
|
| 2750 |
Use `next` and `previous` for sibling relationships. |
| 2751 |
|
| 2752 |
Avoid `id` attributes when relative selectors work. |
| 2753 |
|
| 2754 |
This keeps your HTML cleaner. |
| 2755 |
|
| 2756 |
## Extensions |
| 2757 |
|
| 2758 |
htmx supports extensions to augment its core hypermedia infrastructure. The extension mechanism takes pressure off the core library to add new features, allowing it to focus on its main purpose of generalizing hypermedia controls. |
| 2759 |
|
| 2760 |
For the catalog of core extensions shipped with htmx, see [/extensions](/extensions). |
| 2761 |
|
| 2762 |
### Using Extensions |
| 2763 |
|
| 2764 |
In htmx 4, extensions hook into standard events rather than callback extension points. They are lightweight with no performance penalty. |
| 2765 |
|
| 2766 |
Extensions apply page-wide without requiring `hx-ext` on parent elements. They activate via custom attributes where needed. |
| 2767 |
|
| 2768 |
#### Loading an Extension |
| 2769 |
|
| 2770 |
Include the extension script after htmx. Core extensions ship with htmx in the `/ext/` directory: |
| 2771 |
|
| 2772 |
```html |
| 2773 |
<script src="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/htmx.min.js"></script> |
| 2774 |
<script src="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/ext/hx-sse.js"></script> |
| 2775 |
``` |
| 2776 |
|
| 2777 |
Or with a bundler: |
| 2778 |
|
| 2779 |
```javascript |
| 2780 |
import 'htmx.org'; |
| 2781 |
import 'htmx.org/dist/ext/hx-sse'; |
| 2782 |
``` |
| 2783 |
|
| 2784 |
#### Restricting Extensions |
| 2785 |
|
| 2786 |
To restrict which extensions can register, use an allow list: |
| 2787 |
|
| 2788 |
```html |
| 2789 |
<meta name="htmx-config" content='{"extensions": "my-ext,another-ext"}'> |
| 2790 |
``` |
| 2791 |
|
| 2792 |
When this config is set, only the listed extensions will be loaded. Without it, all registered extensions are active. |
| 2793 |
|
| 2794 |
### Building Extensions |
| 2795 |
|
| 2796 |
htmx 4 introduces an extension system based on event hooks rather than the old callback-based API. |
| 2797 |
|
| 2798 |
#### Defining an Extension |
| 2799 |
|
| 2800 |
Extensions are defined using `htmx.registerExtension()`: |
| 2801 |
|
| 2802 |
```javascript |
| 2803 |
htmx.registerExtension("my-ext", { |
| 2804 |
init: (internalAPI) => { |
| 2805 |
// Called once when extension is registered |
| 2806 |
// Store internalAPI reference if needed |
| 2807 |
}, |
| 2808 |
|
| 2809 |
htmx_before_request: (elt, detail) => { |
| 2810 |
// Called before each request |
| 2811 |
// Return false to cancel |
| 2812 |
}, |
| 2813 |
|
| 2814 |
htmx_after_request: (elt, detail) => { |
| 2815 |
// Called after each request |
| 2816 |
}, |
| 2817 |
}); |
| 2818 |
``` |
| 2819 |
|
| 2820 |
#### Event Hooks |
| 2821 |
|
| 2822 |
Extensions hook into htmx lifecycle events. Event names use underscores instead of colons: |
| 2823 |
|
| 2824 |
##### Core Lifecycle Events |
| 2825 |
|
| 2826 |
| Hook Name | Triggered Event | Parameters | Description | |
| 2827 |
|-----------|----------------|------------|-------------| |
| 2828 |
| `htmx_before_init` | [`htmx:before:init`](/reference/events/htmx-before-init) | `(elt, detail)` | Before element initialization | |
| 2829 |
| `htmx_after_init` | [`htmx:after:init`](/reference/events/htmx-after-init) | `(elt, detail)` | After element initialization | |
| 2830 |
| `htmx_before_process` | [`htmx:before:process`](/reference/events/htmx-before-process) | `(elt, detail)` | Before processing element | |
| 2831 |
| `htmx_after_process` | [`htmx:after:process`](/reference/events/htmx-after-process) | `(elt, detail)` | After processing element | |
| 2832 |
| `htmx_before_cleanup` | [`htmx:before:cleanup`](/reference/events/htmx-before-cleanup) | `(elt, detail)` | Before cleaning up element | |
| 2833 |
| `htmx_after_cleanup` | [`htmx:after:cleanup`](/reference/events/htmx-after-cleanup) | `(elt, detail)` | After cleaning up element | |
| 2834 |
|
| 2835 |
##### Request Lifecycle Events |
| 2836 |
|
| 2837 |
| Hook Name | Triggered Event | Parameters | Description | |
| 2838 |
|-----------|----------------|------------|-------------| |
| 2839 |
| `htmx_config_request` | [`htmx:config:request`](/reference/events/htmx-config-request) | `(elt, detail)` | Configure request before sending | |
| 2840 |
| `htmx_before_request` | [`htmx:before:request`](/reference/events/htmx-before-request) | `(elt, detail)` | Before request is sent | |
| 2841 |
| `htmx_before_response` | `htmx:before:response` | `(elt, detail)` | After fetch, before body consumed | |
| 2842 |
| `htmx_after_request` | [`htmx:after:request`](/reference/events/htmx-after-request) | `(elt, detail)` | After request completes | |
| 2843 |
| `htmx_finally_request` | [`htmx:finally:request`](/reference/events/htmx-finally-request) | `(elt, detail)` | Always called after request | |
| 2844 |
| `htmx_error` | [`htmx:error`](/reference/events/htmx-error) | `(elt, detail)` | On request error | |
| 2845 |
|
| 2846 |
##### Swap Events |
| 2847 |
|
| 2848 |
| Hook Name | Triggered Event | Parameters | Description | |
| 2849 |
|-----------|----------------|------------|-------------| |
| 2850 |
| `htmx_before_swap` | [`htmx:before:swap`](/reference/events/htmx-before-swap) | `(elt, detail)` | Before content swap | |
| 2851 |
| `htmx_after_swap` | [`htmx:after:swap`](/reference/events/htmx-after-swap) | `(elt, detail)` | After content swap | |
| 2852 |
| `htmx_before_settle` | `htmx:before:settle` | `(elt, detail)` | Before settle phase | |
| 2853 |
| `htmx_after_settle` | `htmx:after:settle` | `(elt, detail)` | After settle phase | |
| 2854 |
| `handle_swap` | _(direct call)_ | `(swapStyle, target, fragment, swapSpec)` | Custom swap handler | |
| 2855 |
|
| 2856 |
##### History Events |
| 2857 |
|
| 2858 |
| Hook Name | Triggered Event | Parameters | Description | |
| 2859 |
|-----------|----------------|------------|-------------| |
| 2860 |
| `htmx_before_history_update` | [`htmx:before:history:update`](/reference/events/htmx-before-history-update) | `(elt, detail)` | Before updating history | |
| 2861 |
| `htmx_after_history_update` | [`htmx:after:history:update`](/reference/events/htmx-after-history-update) | `(elt, detail)` | After updating history | |
| 2862 |
| `htmx_after_history_push` | [`htmx:after:history:push`](/reference/events/htmx-after-push-into-history) | `(elt, detail)` | After pushing to history | |
| 2863 |
| `htmx_after_history_replace` | [`htmx:after:history:replace`](/reference/events/htmx-after-replace-into-history) | `(elt, detail)` | After replacing history | |
| 2864 |
| `htmx_before_history_restore` | [`htmx:before:history:restore`](/reference/events/htmx-before-restore-history) | `(elt, detail)` | Before restoring from history | |
| 2865 |
|
| 2866 |
#### Cancelling Events |
| 2867 |
|
| 2868 |
Return `false` or set `detail.cancelled = true` to cancel an event: |
| 2869 |
|
| 2870 |
```javascript |
| 2871 |
htmx.registerExtension("validator", { |
| 2872 |
htmx_before_request: (elt, detail) => { |
| 2873 |
if (!isValid(detail.ctx)) { |
| 2874 |
return false; // Cancel request |
| 2875 |
} |
| 2876 |
}, |
| 2877 |
}); |
| 2878 |
``` |
| 2879 |
|
| 2880 |
#### Internal API |
| 2881 |
|
| 2882 |
The `init` hook receives an internal API object with helper methods: |
| 2883 |
|
| 2884 |
```javascript |
| 2885 |
let api; |
| 2886 |
|
| 2887 |
htmx.registerExtension("my-ext", { |
| 2888 |
init: (internalAPI) => { |
| 2889 |
api = internalAPI; |
| 2890 |
}, |
| 2891 |
|
| 2892 |
htmx_after_init: (elt) => { |
| 2893 |
let value = api.attributeValue(elt, "hx-my-attr"); |
| 2894 |
let specs = api.parseTriggerSpecs("click, keyup delay:500ms"); |
| 2895 |
let { method, action } = api.determineMethodAndAction(elt, evt); |
| 2896 |
}, |
| 2897 |
}); |
| 2898 |
``` |
| 2899 |
|
| 2900 |
Available internal API methods: |
| 2901 |
|
| 2902 |
- `attributeValue(elt, name, defaultVal, returnElt)` - Get htmx attribute value with inheritance |
| 2903 |
- `parseTriggerSpecs(spec)` - Parse trigger specification string |
| 2904 |
- `determineMethodAndAction(elt, evt)` - Get HTTP method and URL |
| 2905 |
- `createRequestContext(elt, evt)` - Create request context object |
| 2906 |
- `collectFormData(elt, form, submitter)` - Collect form data |
| 2907 |
- `handleHxVals(elt, body)` - Process [`hx-vals`](/reference/attributes/hx-vals) attribute |
| 2908 |
|
| 2909 |
#### Request Context |
| 2910 |
|
| 2911 |
The `detail.ctx` object contains request information: |
| 2912 |
|
| 2913 |
```javascript |
| 2914 |
{ |
| 2915 |
sourceElement, // Element triggering request |
| 2916 |
sourceEvent, // Event that triggered request |
| 2917 |
status, // Request status |
| 2918 |
target, // Target element for swap |
| 2919 |
swap, // Swap strategy |
| 2920 |
request: { |
| 2921 |
action, // Request URL |
| 2922 |
method, // HTTP method |
| 2923 |
headers, // Request headers |
| 2924 |
body, // Request body (FormData) |
| 2925 |
validate, // Whether to validate |
| 2926 |
abort, // Function to abort request |
| 2927 |
signal // AbortSignal |
| 2928 |
}, |
| 2929 |
response: { // Available after request |
| 2930 |
raw, // Raw Response object |
| 2931 |
status, // HTTP status code |
| 2932 |
headers // Response headers |
| 2933 |
}, |
| 2934 |
text, // Response text (after request) |
| 2935 |
hx // HX-* response headers (parsed) |
| 2936 |
} |
| 2937 |
``` |
| 2938 |
|
| 2939 |
#### Custom Swap Strategies |
| 2940 |
|
| 2941 |
Extensions can implement custom swap strategies: |
| 2942 |
|
| 2943 |
```javascript |
| 2944 |
htmx.registerExtension("my-swap", { |
| 2945 |
handle_swap: (swapStyle, target, fragment, swapSpec) => { |
| 2946 |
if (swapStyle === "my-custom-swap") { |
| 2947 |
target.appendChild(fragment); |
| 2948 |
return true; // Handled |
| 2949 |
} |
| 2950 |
return false; // Not handled |
| 2951 |
}, |
| 2952 |
}); |
| 2953 |
``` |
| 2954 |
|
| 2955 |
For migrating extensions written for htmx 2.x, see [Migration → Migrating Your Own Extensions](#migrating-your-own-extensions). |
| 2956 |
|
| 2957 |
<hr data-sidebar-group="Security" /> |
| 2958 |
|
| 2959 |
## Best Practices |
| 2960 |
|
| 2961 |
htmx allows you to define logic directly in your DOM. This has a number of advantages, the largest being |
| 2962 |
[Locality of Behavior](/essays/locality-of-behaviour), which makes your system easier to understand and |
| 2963 |
maintain. |
| 2964 |
|
| 2965 |
A concern with this approach, however, is security: since htmx increases the expressiveness of HTML, if a malicious |
| 2966 |
user is able to inject HTML into your application, they can leverage this expressiveness of htmx to malicious |
| 2967 |
ends. |
| 2968 |
|
| 2969 |
### Rule 1: Escape All User Content |
| 2970 |
|
| 2971 |
The first rule of HTML-based web development has always been: *do not trust input from the user*. You should escape all |
| 2972 |
3rd party, untrusted content that is injected into your site. This is to prevent, among other issues, |
| 2973 |
[XSS attacks](https://en.wikipedia.org/wiki/Cross-site_scripting). |
| 2974 |
|
| 2975 |
There is extensive documentation on XSS and how to prevent it on the |
| 2976 |
excellent [OWASP Website](https://owasp.org/www-community/attacks/xss/), |
| 2977 |
including |
| 2978 |
a [Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html). |
| 2979 |
|
| 2980 |
The good news is that this is a very old and well understood topic, and the vast majority of server-side templating |
| 2981 |
languages |
| 2982 |
support [automatic escaping](https://docs.djangoproject.com/en/4.2/ref/templates/language/#automatic-html-escaping) of |
| 2983 |
content to prevent just such an issue. |
| 2984 |
|
| 2985 |
That being said, there are times people choose to inject HTML more dangerously, often via some sort of `raw()` |
| 2986 |
mechanism in their templating language. This can be done for good reasons, but if the content being injected is coming |
| 2987 |
from a 3rd party then it _must_ be scrubbed, including removing attributes starting with `hx-` and `data-hx`, as well as |
| 2988 |
inline `<script>` tags, etc. |
| 2989 |
|
| 2990 |
If you are injecting raw HTML and doing your own escaping, a best practice is to *whitelist* the attributes and tags you |
| 2991 |
allow, rather than to blacklist the ones you disallow. |
| 2992 |
|
| 2993 |
### htmx Security Tools |
| 2994 |
|
| 2995 |
Of course, bugs happen and developers are not perfect, so it is good to have a layered approach to security for |
| 2996 |
your web application, and htmx provides tools to help secure your application as well. |
| 2997 |
|
| 2998 |
Let's take a look at them. |
| 2999 |
|
| 3000 |
#### `hx-ignore` |
| 3001 |
|
| 3002 |
The first tool htmx provides to help further secure your application is the [`hx-ignore`](/reference/attributes/hx-ignore) |
| 3003 |
attribute. This attribute will prevent processing of all htmx attributes on a given element, and on all elements within |
| 3004 |
it. So, for example, if you were including raw HTML content in a template (again, this is not recommended!) then you |
| 3005 |
could place a div around the content with the `hx-ignore` attribute on it: |
| 3006 |
|
| 3007 |
```html |
| 3008 |
<div hx-ignore> |
| 3009 |
<%= raw(user_content) %> |
| 3010 |
</div> |
| 3011 |
``` |
| 3012 |
|
| 3013 |
And htmx will not process any htmx-related attributes or features found in that content. This attribute cannot be |
| 3014 |
disabled by injecting further content: if an `hx-ignore` attribute is found anywhere in the parent hierarchy of an |
| 3015 |
element, it will not be processed by htmx. |
| 3016 |
|
| 3017 |
### CSP Options |
| 3018 |
|
| 3019 |
Browsers also provide tools for further securing your web application. The most powerful tool available is a |
| 3020 |
[Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP). Using a CSP you can tell the |
| 3021 |
browser to, for example, not issue requests to non-origin hosts, to not evaluate inline script tags, etc. |
| 3022 |
|
| 3023 |
CSP can be set via an HTTP header or a `<meta>` tag. HTTP headers are preferred, `<meta>` tags |
| 3024 |
do not enforce all directives and scripts that appear before the `<meta>` tag in the document are |
| 3025 |
not covered by it: |
| 3026 |
|
| 3027 |
```http |
| 3028 |
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-<nonce>' |
| 3029 |
``` |
| 3030 |
|
| 3031 |
A full discussion of CSPs is beyond the scope of this document, but |
| 3032 |
the [MDN Article](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) provides a good jumping-off point |
| 3033 |
for exploring this topic. |
| 3034 |
|
| 3035 |
#### Controlling Cross-Origin Requests |
| 3036 |
|
| 3037 |
htmx defaults [`htmx.config.mode`](/reference/config/htmx-config-mode) to `"same-origin"`, which causes the |
| 3038 |
browser to reject any cross-origin fetch, even if an attacker injects an `hx-get` pointing elsewhere. |
| 3039 |
|
| 3040 |
This setting is enforced globally: any `mode` value in a per-element `hx-config` attribute is ignored and |
| 3041 |
reset to the global config value. This means injected markup like |
| 3042 |
`hx-config='{"mode":"cors"}'` cannot widen request scope. |
| 3043 |
|
| 3044 |
If your application legitimately needs CORS (e.g. an API on a different subdomain): |
| 3045 |
|
| 3046 |
1. Set the mode globally: |
| 3047 |
```javascript |
| 3048 |
htmx.config.mode = "cors"; |
| 3049 |
``` |
| 3050 |
2. Lock down reachable origins with `connect-src`: |
| 3051 |
```html |
| 3052 |
<meta http-equiv="Content-Security-Policy" |
| 3053 |
content="connect-src 'self' https://api.example.com"> |
| 3054 |
``` |
| 3055 |
|
| 3056 |
With both in place, htmx can reach your API but injected target URLs to other origins are blocked by CSP. |
| 3057 |
|
| 3058 |
#### hx-csp Extension |
| 3059 |
|
| 3060 |
For sites using CSP script nonces, the [`hx-csp` extension](/extensions/hx-csp) provides deep integration: |
| 3061 |
|
| 3062 |
- Gates all htmx attribute processing behind a per-request nonce, blocking injected htmx attributes |
| 3063 |
- Automatically creates a `'htmx'` [Trusted Types](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API) policy so only htmx can write HTML into DOM sinks |
| 3064 |
- Replaces `new Function()` eval with nonce-based script injection when `safeEval:true` is set, removing the need for `unsafe-eval` |
| 3065 |
|
| 3066 |
See the [hx-csp extension docs](/extensions/hx-csp) for full setup instructions. |
| 3067 |
|
| 3068 |
#### htmx & Eval |
| 3069 |
|
| 3070 |
htmx uses `new Function()` for some optional features: |
| 3071 |
|
| 3072 |
* Event filters |
| 3073 |
* The [`hx-on`](/reference/attributes/hx-on) attribute |
| 3074 |
* Attribute values starting with `js:` or `javascript:` |
| 3075 |
|
| 3076 |
All of these are optional. If you don't use them you can omit `unsafe-eval` from your CSP entirely. |
| 3077 |
|
| 3078 |
If you do use these features, the [`hx-csp` extension](/extensions/hx-csp) with `safeEval:true` replaces |
| 3079 |
`new Function()` with nonce-based script injection, enabling them without `unsafe-eval`. |
| 3080 |
|
| 3081 |
#### CSP & Inline Styles |
| 3082 |
|
| 3083 |
htmx injects its indicator CSS using [Constructable Stylesheets](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/CSSStyleSheet) (`document.adoptedStyleSheets`), which are not subject to `style-src` CSP restrictions. |
| 3084 |
|
| 3085 |
The one area to be aware of is morph swaps when used alongside JS frameworks like Alpine that set `style` attributes via JavaScript. During morph, htmx reconciles attributes between the old and new element, including any `style` value. Under a strict `style-src` policy without `'unsafe-inline'`, this `setAttribute("style", ...)` call will produce a CSP violation. |
| 3086 |
|
| 3087 |
Add `"style"` to [`morphIgnore`](/reference/config/htmx-config-morphIgnore) to skip it: |
| 3088 |
|
| 3089 |
```html |
| 3090 |
<meta name="htmx-config" content='{"morphIgnore":["data-htmx-powered","style"]}'> |
| 3091 |
``` |
| 3092 |
|
| 3093 |
Class-based CSS transitions continue to work normally. |
| 3094 |
|
| 3095 |
### CSRF Prevention |
| 3096 |
|
| 3097 |
The assignment and checking of CSRF tokens are typically backend responsibilities, but `htmx` can support returning the |
| 3098 |
CSRF token automatically with every request using the [`hx-headers`](/reference/attributes/hx-headers) attribute. The attribute needs to be added to the |
| 3099 |
element issuing the request or one of its ancestor elements. This makes the `html` and `body` elements effective |
| 3100 |
global vehicles for adding the CSRF token to the `HTTP` request header, as illustrated below. |
| 3101 |
|
| 3102 |
```html |
| 3103 |
<html lang="en" hx-headers='{"X-CSRF-TOKEN": "CSRF_TOKEN_INSERTED_HERE"}'> |
| 3104 |
: |
| 3105 |
</html> |
| 3106 |
``` |
| 3107 |
|
| 3108 |
The above elements are usually unique in an HTML document and should be easy to locate within templates. |
| 3109 |
|
| 3110 |
## Caching |
| 3111 |
|
| 3112 |
htmx works with standard [HTTP caching](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching) |
| 3113 |
mechanisms out of the box. |
| 3114 |
|
| 3115 |
If your server adds the |
| 3116 |
[`Last-Modified`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified) |
| 3117 |
HTTP response header to the response for a given URL, the browser will automatically add the |
| 3118 |
[`If-Modified-Since`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since) |
| 3119 |
request HTTP header to the next requests to the same URL. |
| 3120 |
|
| 3121 |
For polling use cases where you want the server to skip responses when content hasn't changed, see the [`ptag` extension](/extensions/hx-ptag). |
| 3122 |
|
| 3123 |
Be mindful that if your server can render different content for the same URL depending on some other |
| 3124 |
headers, you need to use the [`Vary`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching#vary) |
| 3125 |
response HTTP header. |
| 3126 |
|
| 3127 |
For example, if your server renders the full HTML when the [`HX-Request`](/reference/headers/HX-Request) header is missing or `false`, and it renders a |
| 3128 |
fragment of that HTML when `HX-Request: true`, you need to add `Vary: HX-Request`. That causes the cache to be keyed |
| 3129 |
based on a composite of the response URL and the `HX-Request` request header rather than being based just on the |
| 3130 |
response URL. |
| 3131 |
|
| 3132 |
<hr data-sidebar-group="Troubleshoot" /> |
| 3133 |
|
| 3134 |
## Debugging |
| 3135 |
|
| 3136 |
Declarative and event driven programming with htmx (or any other declarative language) can be a wonderful and highly |
| 3137 |
productive |
| 3138 |
activity, but one disadvantage when compared with imperative approaches is that it can be trickier to debug. |
| 3139 |
|
| 3140 |
Figuring out why something *isn't* happening, for example, can be difficult if you don't know the tricks. |
| 3141 |
|
| 3142 |
Here are some tips: |
| 3143 |
|
| 3144 |
Errors and warnings flow to `console.error` / `console.warn` by default. To also see every event htmx dispatches, set `htmx.config.logAll = true`: |
| 3145 |
|
| 3146 |
```javascript |
| 3147 |
htmx.config.logAll = true; |
| 3148 |
``` |
| 3149 |
|
| 3150 |
Observability tools (Sentry, DataDog RUM, LogRocket, etc.) capture `console.*` automatically, so htmx logs flow into your existing pipeline without any extra setup. |
| 3151 |
|
| 3152 |
Of course, that won't tell you why htmx *isn't* doing something. You might also not know *what* events a DOM |
| 3153 |
element is firing to use as a trigger. To address this, you can use the |
| 3154 |
[`monitorEvents()`](https://developers.google.com/web/updates/2015/05/quickly-monitor-events-from-the-console-panel) |
| 3155 |
method available in the |
| 3156 |
browser console: |
| 3157 |
|
| 3158 |
```javascript |
| 3159 |
monitorEvents(htmx.find("#theElement")); |
| 3160 |
``` |
| 3161 |
|
| 3162 |
This will spit out all events that are occurring on the element with the id `theElement` to the console, and allow you |
| 3163 |
to see exactly what is going on with it. |
| 3164 |
|
| 3165 |
Note that this *only* works from the console, you cannot embed it in a script tag on your page. |
| 3166 |
|
| 3167 |
Finally, push come shove, you might want to just debug `htmx.js` by loading up the unminimized version. |
| 3168 |
|
| 3169 |
You would most likely want to set a break point in the methods to see what's going on. |
| 3170 |
|
| 3171 |
And always feel free to jump on the [Discord](https://htmx.org/discord) if you need help. |
| 3172 |
|
| 3173 |
## Configuration |
| 3174 |
|
| 3175 |
Htmx has configuration options that can be accessed either programmatically or declaratively. |
| 3176 |
|
| 3177 |
They are listed below: |
| 3178 |
|
| 3179 |
<div class="info-table"> |
| 3180 |
|
| 3181 |
| Config Variable | Info | |
| 3182 |
|-----------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |
| 3183 |
| `htmx.config.logAll` | defaults to `false`, if set to `true` htmx will log all events to the console for debugging | |
| 3184 |
| `htmx.config.prefix` | defaults to `"data-hx-"`, a secondary attribute prefix recognised alongside the always-active `hx-` prefix (e.g. `data-hx-get` works by default). Set to `""` to disable. **Must be set via meta tag**, setting this after page load will not apply correctly. | |
| 3185 |
| `htmx.config.transitions` | defaults to `false`, whether to use view transitions when swapping content (if browser supports it) | |
| 3186 |
| `htmx.config.history` | defaults to `true`, whether to enable history support. Set to `"reload"` to do a full page reload on history navigation instead of an AJAX request | |
| 3187 |
| `htmx.config.mode` | defaults to `'same-origin'`, the fetch mode for AJAX requests. Can be `'cors'`, `'no-cors'`, or `'same-origin'` | |
| 3188 |
| `htmx.config.defaultSwap` | defaults to `innerHTML` | |
| 3189 |
| `htmx.config.indicatorClass` | defaults to `htmx-indicator` | |
| 3190 |
| `htmx.config.requestClass` | defaults to `htmx-request` | |
| 3191 |
| `htmx.config.includeIndicatorCSS` | defaults to `true` (determines if the indicator styles are loaded) | |
| 3192 |
| `htmx.config.defaultTimeout` | defaults to `60000` (60 seconds), the number of milliseconds a request can take before automatically being terminated | |
| 3193 |
| `htmx.config.inlineScriptNonce` | defaults to `''`, meaning that no nonce will be added to inline scripts | |
| 3194 |
| `htmx.config.extensions` | defaults to `''`, a comma-separated list of extension names to load (e.g., `'preload,optimistic'`) | |
| 3195 |
| `htmx.config.morphIgnore` | defaults to `["data-htmx-powered"]`, array of attribute name prefixes to preserve when morphing elements | |
| 3196 |
| `htmx.config.morphScanLimit` | limits the number of nodes scanned during morphing | |
| 3197 |
| `htmx.config.morphSkip` | defaults to `'[hx-morph-skip]'`, CSS selector for elements to completely skip during morphing (they stay frozen) | |
| 3198 |
| `htmx.config.morphSkipChildren` | defaults to `'[hx-morph-skip-children]'`, CSS selector for elements whose attributes update but children are preserved during morphing | |
| 3199 |
| `htmx.config.noSwap` | defaults to `[204, 304]`, array of HTTP status codes that should not trigger a swap | |
| 3200 |
| `htmx.config.implicitInheritance` | defaults to `false`, if set to `true` attributes will be inherited from parent elements automatically without requiring the `:inherited` modifier | |
| 3201 |
| `htmx.config.defaultFocusScroll` | defaults to `false`, whether to scroll focused elements into view after swap | |
| 3202 |
| `htmx.config.defaultSettleDelay` | defaults to `1` (ms), delay between swap and settle phases | |
| 3203 |
| `htmx.config.metaCharacter` | defaults to `undefined`, allows you to use a custom character instead of `:` for attribute modifiers (e.g., `-` to use `hx-get-inherited` instead of `hx-get:inherited`) | |
| 3204 |
|
| 3205 |
</div> |
| 3206 |
|
| 3207 |
You can set most options directly in JavaScript, or you can use a `meta` tag (accepts [HCON](#hcon) or JSON): |
| 3208 |
|
| 3209 |
> **Note:** Some options are read only once during initialisation and must be set via the `meta` tag to take effect. These include `prefix`, `extensions`, and `metaCharacter`. |
| 3210 |
|
| 3211 |
```html |
| 3212 |
<meta name="htmx-config" content='{"defaultSwap":"innerHTML"}'> |
| 3213 |
``` |
| 3214 |
|
| 3215 |
### Conclusion |
| 3216 |
|
| 3217 |
And that's it! |
| 3218 |
|
| 3219 |
Have fun with htmx! |
| 3220 |
|
| 3221 |
You can accomplish [quite a bit](/patterns) without writing a lot of code! |
| 3222 |
|
| 3223 |
<hr data-sidebar-group="Editor Support" /> |
| 3224 |
|
| 3225 |
## VS Code |
| 3226 |
The [HTMX Toolkit](https://marketplace.visualstudio.com/items?itemName=atoolz.htmx-vscode-toolkit) extension adds htmx support to Visual Studio Code with autocomplete, hover documentation, and snippets. |
| 3227 |
|
| 3228 |
### Features |
| 3229 |
|
| 3230 |
- Attribute autocomplete for all htmx attributes (`hx-get`, `hx-post`, `hx-target`, etc.) |
| 3231 |
- Hover documentation with links to the official docs |
| 3232 |
- Snippets for common htmx patterns |
| 3233 |
- Support for htmx 2.x and 4.x |
| 3234 |
|
| 3235 |
### Installing |
| 3236 |
|
| 3237 |
Search for **HTMX Toolkit** in the VS Code Extensions panel, or install from the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=atoolz.htmx-vscode-toolkit). |
| 3238 |
|
| 3239 |
### Source |
| 3240 |
|
| 3241 |
The extension source code is maintained at [atoolz/htmx-vscode-toolkit](https://github.com/atoolz/htmx-vscode-toolkit). |
| 3242 |
|
| 3243 |
<style>{`[data-sidebar-group] { display: none; }`}</style> |