| 1 | --- |
| 2 | title: "hx-live" |
| 3 | description: "Add lightweight reactivity backed by the DOM" |
| 4 | category: "UX" |
| 5 | icon: "icon-[mdi--lightning-bolt]" |
| 6 | keywords: ["live", "reactive", "bind", "q", "selector"] |
| 7 | --- |
| 8 | |
| 9 | Expressions live in HTML attributes. They read from the page, write to it, and re-run as it changes. |
| 10 | |
| 11 | ```html |
| 12 | <input type="text"> |
| 13 | <p :text="'Hello, ' + q('previous input').value"></p> |
| 14 | ``` |
| 15 | |
| 16 | The paragraph updates as you type. |
| 17 | |
| 18 | ## Installing |
| 19 | |
| 20 | ```html |
| 21 | <script src="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/htmx.min.js"></script> |
| 22 | <script src="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/ext/hx-live.min.js"></script> |
| 23 | ``` |
| 24 | |
| 25 | ## Attributes |
| 26 | |
| 27 | ### `:<attr>` |
| 28 | |
| 29 | Prefix any HTML attribute with `:` and put an expression in it. The result is written to the attribute. |
| 30 | |
| 31 | ```html |
| 32 | <input id="name"> |
| 33 | <button :disabled="!q('#name').value">Submit</button> |
| 34 | ``` |
| 35 | |
| 36 | The same shape works for any attribute: |
| 37 | |
| 38 | ```html |
| 39 | <a :href="'/users/' + q('#user-id').value">profile</a> |
| 40 | <button :hidden="q('.row').count === 0">Clear all</button> |
| 41 | <input :required="q('#mode').value === 'final'"> |
| 42 | ``` |
| 43 | |
| 44 | > ⚠️ **Alpine.js conflict:** The `:` short form uses the same syntax as Alpine.js (`x-bind:`). If Alpine is detected on the page at initialization time, hx-live automatically disables the `:` short form and logs a console warning. You can override this behavior by explicitly setting [`config.live.bindPrefix`](#configlivebindprefix). |
| 45 | |
| 46 | How each attribute is written (booleans, ARIA, property-backed, generic) is described in [Attribute writing rules](#attribute-writing-rules). |
| 47 | |
| 48 | ### `hx-live:<attr>` |
| 49 | |
| 50 | The full form. Behaves identically to `:<attr>`. |
| 51 | |
| 52 | ```html |
| 53 | <button hx-live:disabled="!q('#name').value">Submit</button> |
| 54 | ``` |
| 55 | |
| 56 | Use it if your build pipeline strips `:`-prefixed attributes. |
| 57 | |
| 58 | ### `:.<class>` |
| 59 | |
| 60 | Bind a single class to an expression. Truthy adds it, falsy removes it. |
| 61 | |
| 62 | ```html |
| 63 | <input type="number" value="0"> |
| 64 | <p :.warn="q('previous input').valueAsNumber < 0">Negative balance</p> |
| 65 | ``` |
| 66 | |
| 67 | ### `:class` |
| 68 | |
| 69 | String form: set the listed classes. |
| 70 | |
| 71 | ```html |
| 72 | <input type="number" value="0"> |
| 73 | <div :class="q('previous input').valueAsNumber < 18 ? 'warn big' : 'ok'"></div> |
| 74 | ``` |
| 75 | |
| 76 | Object form: each key is added or removed by the truthiness of its value. |
| 77 | |
| 78 | ```html |
| 79 | <input type="number" value="0"> |
| 80 | <div :class="{ |
| 81 | warn: q('previous input').valueAsNumber < 18, |
| 82 | ok: q('previous input').valueAsNumber >= 18 |
| 83 | }"></div> |
| 84 | ``` |
| 85 | |
| 86 | A key may list several classes that share one condition. Quote the key when it contains spaces. |
| 87 | |
| 88 | ```html |
| 89 | <input id="strict" type="checkbox"> |
| 90 | <div :class="{ 'warn big': q('#strict').checked }">Notice</div> |
| 91 | ``` |
| 92 | |
| 93 | `:class` only manages classes it writes. Other classes set in HTML are untouched. If a class appears both statically and in the binding, the binding wins. |
| 94 | |
| 95 | ### `:text` |
| 96 | |
| 97 | Bind the element's [`textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent) to an expression. |
| 98 | |
| 99 | ```html |
| 100 | <input type="number" value="2"> |
| 101 | <input type="number" value="3"> |
| 102 | <p :text="q('first input').valueAsNumber * q('last input').valueAsNumber"></p> |
| 103 | ``` |
| 104 | |
| 105 | Numbers and other non-strings are stringified. |
| 106 | |
| 107 | ### `:html` |
| 108 | |
| 109 | Bind the element's [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) to an expression. |
| 110 | |
| 111 | ```html |
| 112 | <input value="world"> |
| 113 | <div :html="`<b>${q('previous input').value}</b>`"></div> |
| 114 | ``` |
| 115 | |
| 116 | Make sure to sanitize anything untrusted. |
| 117 | |
| 118 | ### `:style` |
| 119 | |
| 120 | String form: a CSS declaration string. |
| 121 | |
| 122 | ```html |
| 123 | <input id="pct" type="range" value="50"> |
| 124 | <div :style="`width: ${q('#pct').value}%; height: 8px; background: tomato`"></div> |
| 125 | ``` |
| 126 | |
| 127 | Object form: each key sets a CSS property. Camel-case keys convert to kebab-case. |
| 128 | |
| 129 | ```html |
| 130 | <input id="pct" type="range" value="50"> |
| 131 | <input id="color" type="color" value="#ff0000"> |
| 132 | <div :style="{ |
| 133 | width: q('#pct').value + '%', |
| 134 | backgroundColor: q('#color').value, |
| 135 | height: '8px' |
| 136 | }"></div> |
| 137 | ``` |
| 138 | |
| 139 | `:style` only manages properties it writes. Other inline style properties are untouched. If a property appears both statically and in the binding, the binding wins. |
| 140 | |
| 141 | ### `hx-live` |
| 142 | |
| 143 | An escape hatch. Use it when no single `:<attr>` fits, or for multi-step logic and side effects. |
| 144 | |
| 145 | ```html |
| 146 | <input placeholder="search"> |
| 147 | <div hx-live=" |
| 148 | let term = q('previous input').value; |
| 149 | if (!term) { this.textContent = ''; return; } |
| 150 | await debounce(250); |
| 151 | this.textContent = await fetch('/search?q=' + encodeURIComponent(term)) |
| 152 | .then(r => r.text()); |
| 153 | "></div> |
| 154 | ``` |
| 155 | |
| 156 | ## Helpers |
| 157 | |
| 158 | The helpers work inside `hx-live` expressions, inside [`hx-on`](/reference/attributes/hx-on) event handlers, and from regular JavaScript via `htmx.live.*`. |
| 159 | |
| 160 | ```js |
| 161 | htmx.live.q('.row').attr('hidden', true); |
| 162 | ``` |
| 163 | |
| 164 | Inside expressions, `this` is the element, the full htmx API is available unprefixed, and `await` works at the top level (expressions are `async` functions). |
| 165 | |
| 166 | ```html |
| 167 | <button hx-on:click=" |
| 168 | attr('disabled', true); |
| 169 | await ajax('POST', '/save'); |
| 170 | attr('disabled', false); |
| 171 | ">Save</button> |
| 172 | ``` |
| 173 | |
| 174 | ### `q()` |
| 175 | |
| 176 | `q()` returns a proxy over a set of elements. Read from the first match, write to all. |
| 177 | |
| 178 | ```js |
| 179 | q('.row') // every .row in the document |
| 180 | q('#bar') // single element by id |
| 181 | q(element) // wrap an existing element |
| 182 | q(nodeList) // wrap a collection |
| 183 | |
| 184 | q('.row').count // number of matches |
| 185 | q('.row').arr() // Array<Element> |
| 186 | for (let e of q('.row')) {...} // iterate |
| 187 | |
| 188 | q('input').value // value of the first match |
| 189 | q('input').value = '' // assign to every match |
| 190 | |
| 191 | q('.row').classList.add('done') // method calls chain through |
| 192 | q('.row').dataset.state = 'on' |
| 193 | q('button').click() |
| 194 | ``` |
| 195 | |
| 196 | **Selector grammar** |
| 197 | |
| 198 | ```js |
| 199 | q('first .foo') // first match in document order |
| 200 | q('last .foo') // last match |
| 201 | q('next .foo') // first match after this element |
| 202 | q('previous .foo') // closest match before this element |
| 203 | q('closest .foo') // nearest ancestor matching .foo |
| 204 | q('.foo in #scope') // restrict to a specific root |
| 205 | q('.foo in this') // restrict to the current element |
| 206 | ``` |
| 207 | |
| 208 | `next`, `previous`, and `closest` resolve against `this` (the element that owns the expression). They only work inside `hx-live` / `hx-on` scopes. |
| 209 | |
| 210 | **Chaining** |
| 211 | |
| 212 | `.q(...)` on a proxy re-runs the grammar with each element as the anchor: |
| 213 | |
| 214 | ```js |
| 215 | q('.error').q('closest .field') // surrounding .field of each .error |
| 216 | q('section').q('first .item') // first .item per section |
| 217 | q('.row').q('next .row') // each row's successor |
| 218 | ``` |
| 219 | |
| 220 | For plain descendant queries, CSS is shorter: `q('.card .title')` and `q('.card').q('.title')` are equivalent. Use chaining when you need a directional per matched element. |
| 221 | |
| 222 | **Built-in methods** |
| 223 | |
| 224 | The helpers below also work as methods on the proxy, applying across all matched elements: |
| 225 | |
| 226 | ```js |
| 227 | q('input').attr('disabled', true) // set attribute on all |
| 228 | q('.row').toggle('.selected') // toggle class on each |
| 229 | q('.tab.active').take('.active', '.tab') // move a class from peers to self |
| 230 | q('.tab').trigger('select', { id: 1 }) // CustomEvent on each |
| 231 | q('.list').insert('end', '<li>new</li>') // before / after / start / end |
| 232 | ``` |
| 233 | |
| 234 | ### `attr(name, value?)` |
| 235 | |
| 236 | Get or set an attribute, class, or property on this element. Pass one argument to read, two to write. |
| 237 | |
| 238 | ```js |
| 239 | attr('hidden') // is hidden present? |
| 240 | attr('hidden', true) // add (false/null/undefined removes) |
| 241 | attr('.active') // has class .active? |
| 242 | attr('.active', q('#src').checked) // add/remove class |
| 243 | attr('class', 'foo bar') // multi-class string |
| 244 | attr('class', { active: matches('.tab') }) // multi-class object |
| 245 | attr('aria-expanded', matches('.open')) // any aria-*: writes "true"/"false" |
| 246 | attr('value', 'hello') // value/checked/selected: syncs property + attribute |
| 247 | attr('data-x', null) // remove |
| 248 | ``` |
| 249 | |
| 250 | ### `toggle(name, values?)` |
| 251 | |
| 252 | Toggle (no `values`) or cycle (with `values`) a class or attribute on this element. |
| 253 | |
| 254 | ```js |
| 255 | toggle('.active') // toggle class |
| 256 | toggle('aria-expanded') // flip "true" ↔ "false" |
| 257 | toggle('hidden') // toggle attribute presence |
| 258 | toggle('data-view', 'grid|list|table') // cycle attribute through values |
| 259 | toggle('.size', 'sm|md|lg') // cycle classes (only one at a time) |
| 260 | toggle('data-open', 'on|') // cycle: 'on' ↔ absent |
| 261 | ``` |
| 262 | |
| 263 | `values` accepts a `|`-separated string or an array. |
| 264 | |
| 265 | ### `take(name, scope?)` |
| 266 | |
| 267 | Move a class or attribute from siblings to this element. Pass a `scope` selector to widen or restrict the source set. |
| 268 | |
| 269 | ```js |
| 270 | take('.selected', '.tab') // become the selected tab among .tab |
| 271 | take('aria-current', 'nav a') // become the current nav item |
| 272 | take('.active') // implicit scope: parent element's subtree |
| 273 | ``` |
| 274 | |
| 275 | ### `data` |
| 276 | |
| 277 | Read or write `data-*` attributes on the closest ancestor that has them. Lets components share state up the tree. |
| 278 | |
| 279 | ```html |
| 280 | <div data-size="medium"> |
| 281 | <button hx-on:click="data.size = 'small'">S</button> |
| 282 | <button hx-on:click="data.size = 'medium'">M</button> |
| 283 | <button hx-on:click="data.size = 'large'">L</button> |
| 284 | <p :text="`Size: ${data.size}`"></p> |
| 285 | </div> |
| 286 | ``` |
| 287 | |
| 288 | `data.foo` reads from the closest `[data-foo]` ancestor. Writing assigns to that ancestor too. |
| 289 | |
| 290 | Values are automatically JSON-serialized on write and parsed on read. Booleans, numbers, arrays, and objects round-trip transparently: |
| 291 | |
| 292 | ```html |
| 293 | <div data-count="1" data-active="false" data-cart="[]"> |
| 294 | <input id="sku" placeholder="Product code"> |
| 295 | <button hx-on:click="data.cart = [...data.cart, {sku: q('#sku').value, qty: data.count}]">Add to cart</button> |
| 296 | <button hx-on:click="data.count++">+</button> |
| 297 | <button hx-on:click="data.count--">−</button> |
| 298 | <button hx-on:click="data.active = !data.active">Toggle details</button> |
| 299 | <p :text="`Qty: ${data.count} | ${data.cart.length} items in cart`"></p> |
| 300 | </div> |
| 301 | ``` |
| 302 | |
| 303 | Plain strings that aren't valid JSON are returned as-is. |
| 304 | |
| 305 | The `data` proxy is enumerable. Object spread, rest destructuring, and `Object.keys()`/`Object.entries()` use the same cascading lookup rules: |
| 306 | |
| 307 | ```html |
| 308 | <section data-x="1" data-y="2"> |
| 309 | <button data-y="3" |
| 310 | hx-post="/cursor" |
| 311 | hx-vals="js:{ ...data }"> |
| 312 | Send cursor |
| 313 | </button> |
| 314 | </section> |
| 315 | ``` |
| 316 | |
| 317 | Here, `hx-vals` receives `{ x: 1, y: 3 }`. |
| 318 | |
| 319 | `data` is also available on `q()` proxies via `q(selector).data`. It cascades from the first matched element: |
| 320 | |
| 321 | ```js |
| 322 | q('#cart-panel').data.items // read: JSON-parsed value from closest [data-items] ancestor |
| 323 | q('#cart-panel').data.items = [{id: 1}] // write: JSON-stringified to that ancestor |
| 324 | ``` |
| 325 | |
| 326 | For direct, this-only access, use `this.dataset` instead (note: `this.dataset` is always strings). For per-element writes across a set, use `q('.row').dataset.state = 'on'`. |
| 327 | |
| 328 | Because `:<attr>` works on `data-*`, you can also store derived values in the DOM: |
| 329 | |
| 330 | ```html |
| 331 | <div data-first="Ada" data-last="Lovelace" |
| 332 | :data-full="data.first + ' ' + data.last"> |
| 333 | <span :text="data.full"></span> |
| 334 | </div> |
| 335 | ``` |
| 336 | |
| 337 | ### `style` |
| 338 | |
| 339 | Shorthand for `this.style`. |
| 340 | |
| 341 | ```html |
| 342 | <input type="color" value="#ff0000"> |
| 343 | <button hx-on:click="style.setProperty('--accent', q('previous input').value)">Apply</button> |
| 344 | ``` |
| 345 | |
| 346 | ### `classList` |
| 347 | |
| 348 | Shorthand for `this.classList`. |
| 349 | |
| 350 | ```html |
| 351 | <button hx-on:click="classList.add('shake')">Wiggle</button> |
| 352 | ``` |
| 353 | |
| 354 | ### `matches(selector)` |
| 355 | |
| 356 | Shorthand for `this.matches(selector)`. |
| 357 | |
| 358 | ```html |
| 359 | <button :aria-busy="matches('.htmx-request')" hx-post="/save">Save</button> |
| 360 | ``` |
| 361 | |
| 362 | ### `trigger(type, detail?, bubbles?)` |
| 363 | |
| 364 | Dispatch a `CustomEvent` from this element. |
| 365 | |
| 366 | ```html |
| 367 | <li hx-on:click="trigger('select', { id: this.dataset.id })" data-id="42">Item</li> |
| 368 | ``` |
| 369 | |
| 370 | ### `insert(position, html)` |
| 371 | |
| 372 | Insert an HTML string. Wraps [`insertAdjacentHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML) with friendlier position names: `before` and `after` for siblings, `start` and `end` for children. |
| 373 | |
| 374 | ```js |
| 375 | insert('start', '<li>first</li>') // first child |
| 376 | insert('end', '<li>last</li>') // last child |
| 377 | insert('before', '<hr>') // sibling before |
| 378 | insert('after', '<hr>') // sibling after |
| 379 | ``` |
| 380 | |
| 381 | ```html |
| 382 | <ul hx-on:click="insert('end', '<li>+</li>')">Click to add a row</ul> |
| 383 | ``` |
| 384 | |
| 385 | Sanitize anything untrusted. |
| 386 | |
| 387 | ### `debounce(ms)` |
| 388 | |
| 389 | Wait `ms` milliseconds. If called again on the same element before resolving, the previous call is cancelled. |
| 390 | |
| 391 | ```html |
| 392 | <input placeholder="search"> |
| 393 | <div hx-live=" |
| 394 | await debounce(200); |
| 395 | this.textContent = await fetch('/q?term=' + q('previous input').value).then(r => r.text()); |
| 396 | "></div> |
| 397 | ``` |
| 398 | |
| 399 | Each element has its own channel. |
| 400 | |
| 401 | ### `forEvent(...args)` |
| 402 | |
| 403 | Resolve on the next matching event. Mix event names, milliseconds, intervals, and target elements. First to fire wins. |
| 404 | |
| 405 | ```js |
| 406 | await forEvent('click') // next click on this element |
| 407 | await forEvent('click', 1000) // click OR 1s timeout |
| 408 | await forEvent('a', 'b', '5s') // any number of events / intervals |
| 409 | ``` |
| 410 | |
| 411 | Typical use: wait for a CSS transition to finish, with a safety timeout. |
| 412 | |
| 413 | ```html |
| 414 | <button hx-on:click=" |
| 415 | classList.add('fade-out'); |
| 416 | await forEvent('transitionend', 500); |
| 417 | this.remove(); |
| 418 | ">Dismiss</button> |
| 419 | ``` |
| 420 | |
| 421 | ### `nextFrame()` |
| 422 | |
| 423 | Resolve on the next animation frame. |
| 424 | |
| 425 | ```html |
| 426 | <button hx-on:click=" |
| 427 | classList.remove('shake'); |
| 428 | await nextFrame(); |
| 429 | classList.add('shake'); |
| 430 | ">Replay shake</button> |
| 431 | ``` |
| 432 | |
| 433 | ## ARIA as state |
| 434 | |
| 435 | ARIA attributes serve two purposes: they describe the component to assistive tech, and they hold UI state. |
| 436 | |
| 437 | Bind them with `:aria-*` and drive CSS off the same attribute. You avoid `.is-open`, `.active`, and `.loading` classes. |
| 438 | |
| 439 | | Attribute | Meaning | Typical UI use | |
| 440 | |-----------------|---------------------|---------------------------------------| |
| 441 | | `aria-expanded` | "is open" | Disclosure, menu, accordion | |
| 442 | | `aria-selected` | "is the active one" | Tabs, listbox option | |
| 443 | | `aria-pressed` | "toggle is on" | Toggle button (bold, mute) | |
| 444 | | `aria-checked` | "checkbox state" | Custom checkboxes, radios | |
| 445 | | `aria-busy` | "is loading" | Form during submit, list during fetch | |
| 446 | | `aria-disabled` | "can't interact" | Greyed-out non-button control | |
| 447 | | `aria-current` | "the current one" | Nav item, breadcrumb, step | |
| 448 | | `aria-hidden` | "hidden from a11y" | Decorative content | |
| 449 | |
| 450 | **Disclosure.** |
| 451 | |
| 452 | For a single inline section, native [`<details>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) is the right tool. Use `aria-expanded` when the trigger and target are separated in the DOM. |
| 453 | |
| 454 | ```html |
| 455 | <header> |
| 456 | <button hx-on:click="toggle('aria-expanded')" aria-expanded="false">Menu</button> |
| 457 | </header> |
| 458 | <aside :hidden="!q('header button').attr('aria-expanded')">...</aside> |
| 459 | ``` |
| 460 | |
| 461 | **Toggle button.** |
| 462 | |
| 463 | ```html |
| 464 | <button hx-on:click="toggle('aria-pressed')" aria-pressed="false">Bold</button> |
| 465 | ``` |
| 466 | |
| 467 | ```css |
| 468 | [aria-pressed="true"] { background: lightblue } |
| 469 | ``` |
| 470 | |
| 471 | **Tabs.** |
| 472 | |
| 473 | ```html |
| 474 | <div role="tablist"> |
| 475 | <button role="tab" hx-on:click="take('aria-selected', '[role=tab]')" aria-selected="true">A</button> |
| 476 | <button role="tab" hx-on:click="take('aria-selected', '[role=tab]')">B</button> |
| 477 | <button role="tab" hx-on:click="take('aria-selected', '[role=tab]')">C</button> |
| 478 | </div> |
| 479 | ``` |
| 480 | |
| 481 | `take('aria-selected', '[role=tab]')` writes `"false"` on every `[role=tab]`, then `"true"` on this one. |
| 482 | |
| 483 | **Loading state.** |
| 484 | |
| 485 | ```html |
| 486 | <form :aria-busy="matches('.htmx-request')" hx-post="/save"> |
| 487 | <input name="email"> |
| 488 | <button type="submit">Save</button> |
| 489 | </form> |
| 490 | ``` |
| 491 | |
| 492 | ```css |
| 493 | [aria-busy="true"] { opacity: 0.5; pointer-events: none } |
| 494 | ``` |
| 495 | |
| 496 | **Non-boolean ARIA.** Strings pass through, so `aria-current="page"`, `aria-pressed="mixed"`, and numeric ARIA (`aria-valuenow="50"`) work in the simple form: |
| 497 | |
| 498 | ```html |
| 499 | <a :aria-current="location.pathname === '/home' ? 'page' : false" href="/home">Home</a> |
| 500 | <button :aria-pressed="state.bold ? 'mixed' : !!state.bold">Bold</button> |
| 501 | <div role="slider" :aria-valuenow="q('#slider').valueAsNumber"></div> |
| 502 | ``` |
| 503 | |
| 504 | ## How it works |
| 505 | |
| 506 | ### Re-run triggers |
| 507 | |
| 508 | A single document-wide `MutationObserver` and `input` / `change` listeners trigger a recompute of every live expression. Any of these schedule one: |
| 509 | |
| 510 | - DOM additions, removals, attribute changes, text changes |
| 511 | - `input` or `change` events from any control |
| 512 | - completion of an htmx swap (recomputes pause mid-swap, run once at the end) |
| 513 | |
| 514 | All expressions run in a single microtask, so multiple synchronous mutations coalesce into one recompute. |
| 515 | |
| 516 | ### Self-mutation is safe |
| 517 | |
| 518 | When an expression writes to the DOM, the observer drains its own pending records inside the same microtask. Writes made by `hx-live` cannot trigger a feedback loop. |
| 519 | |
| 520 | ### Runaway cap |
| 521 | |
| 522 | If recomputes exceed 50/sec, the extension logs a warning. Bindings continue running. Tune your expression or add `debounce`. |
| 523 | |
| 524 | ### Coordinating with htmx swaps |
| 525 | |
| 526 | Recomputes are deferred between [`htmx:before:swap`](/reference/events/htmx-before-swap) and [`htmx:swap:finally`](/reference/events/htmx-swap-finally). One consolidated recompute runs when the swap finishes, regardless of how much markup changed. |
| 527 | |
| 528 | ### Cleanup |
| 529 | |
| 530 | When an `hx-live` element is removed, its expression drops out on the next scheduled run. When all expressions are gone, the observer and listeners detach. |
| 531 | |
| 532 | [`hx-ignore`](/reference/attributes/hx-ignore) descendants are not registered. |
| 533 | |
| 534 | ### Boolean, ARIA, and other attribute kinds |
| 535 | |
| 536 | [`:<attr>`](#attr) writes the value differently depending on the attribute, following HTML conventions. |
| 537 | |
| 538 | **Boolean attributes** (`disabled`, `hidden`, `required`, `open`, `readonly`, `inert`, ...). Truthy adds the attribute; falsy removes it. |
| 539 | |
| 540 | ```html |
| 541 | <button :disabled="truthyExpr"> <!-- <button disabled=""> --> |
| 542 | <button :disabled="falsyExpr"> <!-- <button> --> |
| 543 | <div :hidden="truthyExpr"> <!-- <div hidden=""> --> |
| 544 | <div :hidden="falsyExpr"> <!-- <div> --> |
| 545 | <input :required="truthyExpr"> <!-- <input required=""> --> |
| 546 | <input :required="falsyExpr"> <!-- <input> --> |
| 547 | <details :open="truthyExpr"> <!-- <details open=""> --> |
| 548 | <details :open="falsyExpr"> <!-- <details> --> |
| 549 | <input :readonly="truthyExpr"> <!-- <input readonly=""> --> |
| 550 | <input :readonly="falsyExpr"> <!-- <input> --> |
| 551 | <div :inert="truthyExpr"> <!-- <div inert=""> --> |
| 552 | <div :inert="falsyExpr"> <!-- <div> --> |
| 553 | ``` |
| 554 | |
| 555 | **ARIA attributes** (`aria-*`). Strings and numbers pass through (`"mixed"`, `"page"`, `50`). Other values coerce to `"true"` or `"false"` per the [WAI-ARIA spec](https://www.w3.org/TR/wai-aria-1.2/). Never removed. |
| 556 | |
| 557 | ```html |
| 558 | <button :aria-expanded="truthyExpr"> <!-- <button aria-expanded="true"> --> |
| 559 | <button :aria-expanded="falsyExpr"> <!-- <button aria-expanded="false"> --> |
| 560 | <button :aria-pressed="'mixed'"> <!-- <button aria-pressed="mixed"> --> |
| 561 | ``` |
| 562 | |
| 563 | **Stringy enumerated attributes** (`contenteditable`, `draggable`, `spellcheck`). Stringify the value. Accepts strings beyond `true`/`false` for attributes that support them. |
| 564 | |
| 565 | ```html |
| 566 | <div :contenteditable="true"> <!-- <div contenteditable="true"> --> |
| 567 | <div :contenteditable="false"> <!-- <div contenteditable="false"> --> |
| 568 | <div :contenteditable="'plaintext-only'"> <!-- <div contenteditable="plaintext-only"> --> |
| 569 | ``` |
| 570 | |
| 571 | **Property-backed attributes** (`checked`, `value`, `selected`). Sync both the DOM property and the HTML attribute. |
| 572 | |
| 573 | ```html |
| 574 | <input type="checkbox" :checked="true"> <!-- .checked = true, checked="" --> |
| 575 | <input type="checkbox" :checked="false"> <!-- .checked = false, attribute removed --> |
| 576 | <input :value="'hello'"> <!-- .value = "hello", value="hello" --> |
| 577 | ``` |
| 578 | |
| 579 | **Anything else.** Stringify the value. `null`, `undefined`, or `false` remove the attribute. |
| 580 | |
| 581 | ```html |
| 582 | <a :href="'/profile'"> <!-- <a href="/profile"> --> |
| 583 | <a :href="null"> <!-- <a> --> |
| 584 | <a :href="false"> <!-- <a> --> |
| 585 | <a :href="''"> <!-- <a href=""> --> |
| 586 | ``` |
| 587 | |
| 588 | ## Public API |
| 589 | |
| 590 | All [helpers](#helpers) are exposed under `htmx.live.*` for use from regular JavaScript (outside `hx-live` / `hx-on` expressions): |
| 591 | |
| 592 | ```js |
| 593 | htmx.live.q('.row') |
| 594 | htmx.live.attr('.row', 'hidden', true) |
| 595 | htmx.live.take('.tab.active', '.active', '.tab') |
| 596 | ``` |
| 597 | |
| 598 | `htmx.live.refresh()` forces a recompute. Use it when an expression reads from a source the observer cannot see (a JS variable, a getter, an external store) and you've just mutated it. |
| 599 | |
| 600 | ```js |
| 601 | window.appState = 'loading'; |
| 602 | htmx.live.refresh(); |
| 603 | ``` |
| 604 | |
| 605 | Selector directionals (`next`, `previous`, `closest`) need an anchor and only work inside `hx-live` / `hx-on`, not from `htmx.live.q`. |
| 606 | |
| 607 | ## Configuration |
| 608 | |
| 609 | ### `config.live.bindPrefix` |
| 610 | |
| 611 | Controls the short-form prefix for binding attributes. Defaults to `':'` (or disabled automatically if Alpine.js is detected). |
| 612 | |
| 613 | | Value | Effect | Example attribute | |
| 614 | |-------|--------|-------------------| |
| 615 | | undefined (default) | `:attr` enabled, unless Alpine detected | `:hidden`, `:text`, `:.active` | |
| 616 | | `':'` | `:attr` short form forced on | `:hidden`, `:text`, `:.active` | |
| 617 | | `''` or falsy | Short form disabled, only `hx-live:attr` works | `hx-live:hidden` | |
| 618 | | `'hx:'` | Custom prefix | `hx:hidden`, `hx:text`, `hx:.active` | |
| 619 | |
| 620 | The long form `hx-live:<attr>` always works regardless of this setting. |
| 621 | |
| 622 | **Alpine.js auto-detection** |
| 623 | |
| 624 | If `window.Alpine` exists when hx-live initializes and no `bindPrefix` is configured, the `:` short form is automatically disabled and a console warning is logged. To resolve: |
| 625 | |
| 626 | - Use the long form `hx-live:<attr>` (always works) |
| 627 | - Or explicitly set a non-conflicting prefix: |
| 628 | |
| 629 | ```html |
| 630 | <!-- Use hx: as short form instead --> |
| 631 | <meta name="htmx-config" content='{"live":{"bindPrefix":"hx:"}}'> |
| 632 | ``` |
| 633 | |
| 634 | - Or force `:` if you know what you're doing: |
| 635 | |
| 636 | ```html |
| 637 | <meta name="htmx-config" content='{"live":{"bindPrefix":":"}}'> |
| 638 | ``` |
| 639 | |
| 640 | **Manually disabling the short form** |
| 641 | |
| 642 | If Alpine loads after hx-live (or you want to be explicit), disable it yourself: |
| 643 | |
| 644 | ```html |
| 645 | <meta name="htmx-config" content='{"live":{"bindPrefix":""}}'> |
| 646 | ``` |
| 647 | |
| 648 | With `bindPrefix: ''`, use the canonical long form: |
| 649 | |
| 650 | ```html |
| 651 | <!-- Alpine handles :class, hx-live handles hx-live:text --> |
| 652 | <p :class="alpineVar" hx-live:text="q('#name').value"></p> |
| 653 | ``` |
| 654 | |
| 655 | With `bindPrefix: 'hx:'`: |
| 656 | |
| 657 | ```html |
| 658 | <!-- Alpine handles :class, hx-live handles hx:text --> |
| 659 | <p :class="alpineVar" hx:text="q('#name').value"></p> |
| 660 | ``` |
| 661 | |
| 662 | ## Notes |
| 663 | |
| 664 | - Expressions run on any DOM mutation. There is no per-variable tracking. The microtask coalescing keeps this cheap, but expensive expressions should `debounce` or guard themselves. |
| 665 | - The DOM is the source of truth. To share state between expressions, use ARIA attributes, `data-*` attributes (the `data` proxy makes this ergonomic), or hidden inputs. |
| 666 | - When using morph swap styles (`innerMorph` / `outerMorph`), server responses will overwrite `data-*` attributes by default. To preserve client-side state during morphs, add a prefix to `morphIgnore` — e.g. `morphIgnore:["data-"]` will protect all `data-*` attributes from being overwritten. Non-morph swaps (`innerHTML`, `outerHTML`) replace the DOM entirely, so state should live on an ancestor element that isn't swapped. |
| 667 | - Expressions must be safe to run repeatedly. Avoid unconditional `fetch()` calls. Use `debounce` or guard on a value change. |
| 668 | - If your build pipeline strips `:`-prefixed attributes, use the canonical `hx-live:<attr>` form instead. Behavior is identical. |
| 669 | - If using Alpine.js on the same page, hx-live auto-detects it and disables the `:` short form. See [Configuration](#configuration) for details. |
| 670 | |
| 671 | ## See also |
| 672 | |
| 673 | - [`hx-on`](/reference/attributes/hx-on) (attribute) |
| 674 | - [Locality of Behaviour](/essays/locality-of-behaviour) (essay) |