HTMX Documentation

I want to take notes on HTMX documentation because it is what I use as a frontend framework.

Date Created:
Last Edited:
1 55

References



Related


  • Hypertext as the Engine of Application State
    • Hypermedia as the engine of application state (HATEOAS) is a constraint of the REST software architectural style that distinguished it from other network architectural styles. With HATEOASm a client interacts with a network application whose application servers provide information dynamically through hypermedia. A REST client needs little to no prior knowledge about how to interact with an application or server beyond generically understanding of hypermedia.


Notes


HTMX is a library that allows you to access modern browser features directly from HTML, rather than just using JavaScript.

HTMX extends and generalizes the core idea of HTML as hypertext, opening up many mor possibilities directly within the language:

  • Now any element, not just anchors and forms, can issue an HTTP request
  • Now any event, not just clicks and form submissions, can trigger requests
  • Now any HTTP verb, not just GET and POST, can be used
  • Now any element, not just the entire window, can be the target for update by the request

When you use HTMX, you respond with HTML, not JSON. This keeps you firmly within the original web programming model, using Hypertext as the Engine of Application State without even needing to really understand that concept.

You can use HTMX:

  • From a CDN
  • by Self-hosting
  • By installing with npm

The core of HTMX is a set of attributes that allow you to issue AJAX requests directly from HTML. By default, AJAX requests are triggered by the natural event of an element:

  • input, textarea, select are triggered on the change event
  • form is triggered on the submit event
  • everything else is triggered by the click event

If you want different behavior, you can use the hx-trigger attribute to specify which event will cause the request.

<div hx-post="/mouse_entered" hx-trigger="mouseenter once">
[Here Mouse, Mouse!]
</div>

A trigger can also have a few modifiers that change its behavior. For example, if you want a request to only happen once, you can use the once modifier for the trigger. Other modifiers include:

  • changed - only issue a request if the value of the element has changed
  • delay - wait a given amount of time before issuing a request
  • throttle: <time interval> - wait a given amount of time before issuing the request
  • from: <CSS Selector> - listen for the event on a different element

You can also apply trigger filters by using the square brackets after the event name, enclosing a JavaScript expression that will be evaluated. If the expression evaluates to true the event will trigger.

HTMX provides a few special events for use in hx-trigger:

  • load - fires once the element is loaded
  • revealed - fires when an element first scrolls into the viewport
  • intersect - fires once when an element first intersects the viewport. Supports two additional options:
    • root: <selector> -a CSS selector of the root element for intersection
    • thrshold: <float> - a floating point number between 0.0 and 1.0, indicating what amount of intersection to fire the event on

If you want an element to poll the given URL rather than wait for an event, you can use the every syntax with the hx-trigger attribute.

Another technique that can be used to achieve polling in HTMX is load polling, where an element specifies a load trigger along with a delay, and replaces itself with the response:

<div hx-get="/messages"
hx-trigger="load delay:1s"
hx-swap="outerHTML">
</div>

When an AJAX request is issued it is often good to let the user know that something is happening since the browser will not give them any feedback. You can accomplish this with the htmx-indicator class. The htmx-indicator class is defined so that the opacity of any element with this class is 0 by default, making it invisible but present in the DOM.

If you want the response to be loaded into a different element other than the one that made the request, you can use the hx-target attribute, which takes a CSS selector.

hx-target, and most attributes that take a CSS selector, support an extended CSS syntax:

  • You can use the this keyword, which indicates that the element that the hx-target attribute is on is the target
  • The closest <CSS selector> syntax will find the closest ancestor element or itself, that matches the given CSS selector.
  • The next <CSS Selector> syntax will find the next element in the DOM matching the given CSS selector
  • The previous <CSS selector> syntax will find the previous element in the DOM matching the given CSS selector
  • find <CSS selector> which will find the first child descendant element that matches the given CSS selector.

HTMX offers a few different ways to swap the HTML returned into the DOM. By default, the content replaces the innerHTML of the target element. You can modify this by using the hx-swap attribute.

Often you want to coordinate the requests between two elements. For example, you may want a request from one element to supersede the request of another element, or wait until the other element's request has finished. HTMX offers a hx-sync attribute to help you accomplish this.

If you want to swap content from a response directly into the DOM by using the id attribute you can use the hx-swap-oob attribute in the response HTML:

<div id="message" hx-swap-oob="true">Swap me directly!</div>
Additional Content
  • Table elements can be problematic when combined with out of band swaps, because, by the HTML spec, many can't stand on their own in the DOM (e.g., <tr> or <td>)

If you want to select a subset of the response HTML to swap into the target, you can use the hx-select attribute, which takes a CSS selector and selects the matching elements from the response.

If there is content that you wish to be preserved across swaps you can use the hx-preserve attribute you wish to be preserved.

As with HTML forms, the name attribute of the input is used as the parameter name in the request that HTMX sends.

Additionally, if the element causes a non-GET request, the values of all the inputs of the nearest enclosing form will be included.

If you wish to include the values of other elements, you can use the hx-include attribute with a CSS selector of all the elements whose values you want to include in the request.

If you wish to filter out some parameters, you can use the hx-params attribute.

If you wish to upload files via an HTMX request, you can set the hx-encoding attribute to multipart/form-data. HTMX fires a htmx:xhr:progress event periodically on the standard progress event during upload, which you can hook into to show the progress of the upload.

You can include extra values in a request using the hx-vals and hx-vars attributes.

Most attributes in HTMX are inherited: they apply to the element they are on as well as any children elements. This allows you to hoist attributes up to avoid code duplication

HTMX supports boosting regular HTML anchors and forms with the hx-boost attribute. This attribute will convert all anchor tags and forms into AJAX requests that, by default, target the body of the page.

You can check on the server side for the HX-REQUEST header to differentiate between an HTMX-driven and a regular request, to determine exactly what to render to the client.

HTMX provides a simple mechanism for interacting with the browser history API. If you want a given element to push its request URL into the browser navigation bar and add the current state of the page to the browser's history, include the hx-push-url attribute. By default, HTMX will use the body to take and restore the history snapshot from. This is usually the right thing, but if you want to use a narrower element for snapshotting you can use the hx-history-elt attribute to specify a different one.

History snapshotting can be disabled for a URL by setting the hx-history attribute to false on any element in the current document, or any html fragment loaded into the current document by HTMX.

HTMX expects the responses to the AJAX requests it makes to be HTML, typically HTML fragments. HTMX will then swap the returned HTML into the document at the target specified and with the swap strategy specified.

You can configure the response handling behavior of HTMX by mutating or replacing the htmx.config.responseHandling array. This object is a collection of JavaScript objects defined like:

responseHandling: [
  {code:"204", swap: false},   // 204 - No Content by default does nothing, but is not an error
  {code:"[23]..", swap: true}, // 200 & 300 responses are non-errors and are swapped
  {code:"[45]..", swap: false, error:true}, // 400 & 500 responses are not swapped and are errors
  {code:"...", swap: false}    // catch all for any other response code
]

When HTMX receives a response, it will iterate in order over the htmx.config.responseHandling array and test if the code property of a given object, when treated as a Regular Expression, matches the current response. If an entry does match the current response code, it will be used to determine if and how the response will be processed.

Request Headers

HTMX Request Headers

Response Headers

Response Headers

The order of operations in a HTMX request are:

  1. The element is triggered and begins a request
  2. Values are gathered for the request.
  3. The htmx-request class is applied to the appropriate elements.
  4. The request is then issued asynchronously via AJAX
  5. Upon getting a response the target element is marked with the htmx-swapping class
  6. An additional swap delay is applied
  7. The actual content swap is done
    1. The htmx-swapping class is removed from the target.
    2. The htmx-added class is added to each piece of content
    3. The htmx-settling class if applied to the target
    4. A settle delay is done (default: 20ms)
    5. The DOM is settled
    6. The htmx-settling class if removed from the target
    7. The htmx-added class is removed from each piece of new content

HTMX integrates with the HTML5 Validation API and will not issue a request for a form if a validatable input is invalid.

HTMX provides an extensions mechanism that allows you to customize the libraries' behavior. Extensions are defined in JavaScript then enabled via the hx-ext attribute.

HTMX has an extensive events mechanism, which doubles as the logging system.

Comments

You have to be logged in to add a comment

User Comments

Frank Frank
not just clicks and form submissions, can trigger requests

SIZE TEST

1
Frank Frank
not just clicks and form submissions, can trigger requests

SIZE TEST

1

Insert Math Markup

ESC
About Inserting Math Content
Display Style:

Embed News Content

ESC
About Embedding News Content

Embed Youtube Video

ESC
Embedding Youtube Videos

Embed TikTok Video

ESC
Embedding TikTok Videos

Embed X Post

ESC
Embedding X Posts

Embed Instagram Post

ESC
Embedding Instagram Posts

Insert Details Element

ESC

Example Output:

Summary Title
You will be able to insert content here after confirming the title of the <details> element.

Insert Table

ESC
Customization
Align:
Preview:

Insert Horizontal Rule

#000000

Preview:


View Content At Different Sizes

ESC

Edit Style of Block Nodes

ESC

Edit the background color, default text color, margin, padding, and border of block nodes. Editable block nodes include paragraphs, headers, and lists.

#ffffff
#000000

Edit Selected Cells

Change the background color, vertical align, and borders of the cells in the current selection.

#ffffff
Vertical Align:
Border
#000000
Border Style:

Edit Table

ESC
Customization:
Align:

Upload Lexical State

ESC

Upload a .lexical file. If the file type matches the type of the current editor, then a preview will be shown below the file input.

Upload 3D Object

ESC

Upload Jupyter Notebook

ESC

Upload a Jupyter notebook and embed the resulting HTML in the text editor.

Insert Custom HTML

ESC

Edit Image Background Color

ESC
#ffffff

Insert Columns Layout

ESC
Column Type:

Select Code Language

ESC
Select Coding Language

Insert Chart

ESC

Use the search box below

Upload Previous Version of Article State

ESC