HTMX

A modern, minimal JavaScript library that allows you to create dynamic web interfaces using HTML attributes.

#Getting Started

#CDN Import

<script src="https://unpkg.com/[email protected]"></script>

#Basic Usage

<button hx-get="/hello" hx-target="#result">Say Hi</button>
<div id="result"></div>

#Server Response

<!-- /hello response -->
<p>Hello from server</p>

#Core Attributes

#hx-get, hx-post, etc.

<a hx-get="/page">Load Page</a>
<form hx-post="/submit"></form>

#hx-target

<button hx-get="/data" hx-target="#box"></button>
<div id="box"></div>

#hx-trigger

<input
  hx-get="/search"
  hx-trigger="keyup changed delay:300ms"
  hx-target="#results"
/>

#Swap & Out of Band

#hx-swap

<div hx-get="/frag" hx-swap="innerHTML"></div>
  • outerHTML
  • innerHTML
  • beforebegin, afterbegin, etc.

#hx-swap-oob

<div hx-swap-oob="true" id="msg"></div>

Useful for global updates from partials.

#Swap Modifiers

hx-swap="outerHTML transition:true swap:1s"

#Forms & Events

#Auto POST on Submit

<form hx-post="/submit" hx-target="#status">
  <input name="name" />
  <button type="submit">Send</button>
</form>
<div id="status"></div>

#hx-include

<input id="user-id" name="id" />
<button hx-post="/update" hx-include="#user-id">Update</button>

#hx-vals

<button hx-post="/save" hx-vals='{"id": 42, "active": true}'>Save</button>

#Advanced Features

#Loading Indicator

<button hx-get="/load" hx-indicator="#spinner">Load</button>
<div id="spinner" class="htmx-indicator">Loading...</div>

#hx-push-url

<a hx-get="/page" hx-push-url="true">Go</a>

#Polling

<div hx-get="/time" hx-trigger="every 5s"></div>

#Events & Extensions

#Listen to Events

document.body.addEventListener('htmx:afterSwap', (e) => {
  console.log('Swap complete');
});

#Event Hooks

  • htmx:beforeRequest
  • htmx:afterSwap
  • htmx:responseError

#Extensions

<script src="https://unpkg.com/htmx.org/dist/ext/json-enc.js"></script>
<form hx-post="/api" hx-ext="json-enc"></form>

#Example Use Case

#Python Backend (Flask)

@app.route("/hello")
def hello():
    return "<p>Hello, HTMX!</p>"

#HTML Client

<button hx-get="/hello" hx-target="#msg">Click</button>
<div id="msg"></div>