HTMX: Requests, Targets & Swaps
HTMX extends plain HTML with attributes that let any element issue an AJAX request and swap the HTML response directly into the page -- building dynamic UIs largely through server-rendered HTML fragments instead of client-side JavaScript rendering logic.
Basic Requests
<!-- hx-get/post/put/delete map to HTTP methods. Default trigger:
click for most elements, submit for forms, change for inputs -->
<button hx-get="/messages" hx-target="#message-list" hx-swap="innerHTML">
Load messages
</button>
<div id="message-list"><!-- response HTML lands here --></div>
<!-- Forms work the same way -- POST to the server, swap the response -->
<form hx-post="/messages" hx-target="#message-list" hx-swap="beforeend">
<input name="text" placeholder="New message" />
<button type="submit">Send</button>
</form>
<!-- Confirm before a destructive action -->
<button hx-delete="/messages/42" hx-target="closest tr" hx-swap="outerHTML"
hx-confirm="Delete this message?">
Delete
</button>hx-swap Positions
innerHTML (default) -- replaces the target's contents.
outerHTML -- replaces the target element itself.
beforeend / afterbegin -- appends/prepends inside the target.
beforebegin / afterend -- inserts before/after the target element.
swap:1s settle:1s -- delay before swap / before settling classes are removed, giving CSS transitions time to animate.
Triggers & Live Search
<!-- hx-trigger overrides the default event -- here, debounced keyup
instead of the input's default (change) event -->
<input type="search" name="q"
hx-get="/search"
hx-trigger="keyup changed delay:300ms"
hx-target="#results" />
<div id="results"></div>
<!-- hx-indicator toggles a loading spinner automatically for the
duration of the request -- no manual show/hide JS needed -->
<button hx-get="/report" hx-indicator="#spinner">Generate report</button>
<img id="spinner" class="htmx-indicator" src="/spinner.gif" />
<!-- hx-vals adds extra parameters beyond the element's own inputs -->
<button hx-get="/items" hx-vals='{"category": "electronics"}'>Filter</button>Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free