htmx Core Attributes

Core attributes are the primary way to use htmx. They allow you to issue AJAX requests and update parts of your page declaratively.

Attribute Description Example
hx-get Issues a GET request to the specified URL and swaps the response into the target element. <button hx-get="/hello">Say Hello</button>
hx-post Issues a POST request to the specified URL and swaps the response into the target element. <form hx-post="/submit">...</form>
hx-put Issues a PUT request to the specified URL and swaps the response into the target element. <button hx-put="/update">Update</button>
hx-delete Issues a DELETE request to the specified URL and swaps the response into the target element. <button hx-delete="/delete">Delete</button>
hx-patch Issues a PATCH request to the specified URL and swaps the response into the target element. <button hx-patch="/patch">Patch</button>
hx-target Specifies the element to swap the response into. Can be a CSS selector or this for the current element. <button hx-get="/hello" hx-target="#result">Say Hello</button>
hx-swap Controls how the response is swapped into the target element (e.g., innerHTML, outerHTML, beforeend, etc.). <div hx-get="/msg" hx-swap="outerHTML">...</div>
hx-trigger Specifies the event(s) that trigger the request (e.g., click, change, load, or custom events). <input hx-get="/search" hx-trigger="keyup changed delay:500ms">
hx-vals Specifies additional parameters to submit with the request, as a JSON object or a JavaScript expression. <button hx-post="/vote" hx-vals='{"option":"A"}'>Vote A</button>
hx-include Specifies additional elements whose values should be included in the request. <button hx-post="/submit" hx-include="#other-input">Submit</button>
hx-params Controls which parameters are submitted with the request (e.g., none, not, or a space-separated list). <form hx-post="/submit" hx-params="not password">...</form>
hx-headers Specifies additional headers to send with the request, as a JSON object or JavaScript expression. <button hx-get="/data" hx-headers='{"X-API-Key":"123"}'>Get Data</button>
hx-push-url Pushes the request URL into the browser history (or replaces it) when the request completes. <a hx-get="/page2" hx-push-url="true">Next Page</a>
hx-select Specifies a CSS selector to select a portion of the response to swap into the target. <div hx-get="/fragment" hx-select="#main">...</div>
hx-confirm Shows a confirmation dialog before issuing the request. If the user cancels, the request is not sent. <button hx-delete="/item" hx-confirm="Are you sure?">Delete</button>
hx-disable Disables the element while the request is in flight. <button hx-post="/submit" hx-disable>Submit</button>
hx-indicator Specifies an element to show while the request is in flight (e.g., a loading spinner). <button hx-get="/data" hx-indicator="#spinner">Load</button>
hx-encoding Specifies the encoding type for the request (e.g., multipart/form-data for file uploads). <form hx-post="/upload" hx-encoding="multipart/form-data">...</form>
hx-ext Enables one or more htmx extensions for the element. <div hx-ext="debug">...</div>

htmx Additional Attributes

Additional attributes provide further control and customization for htmx behavior. These are not as commonly used as the core attributes, but can be very useful for advanced scenarios.

Attribute Description Example
hx-boost Enables AJAX navigation for links and forms within the element. Set to true to activate. <body hx-boost="true">...</body>
hx-disable Disables htmx processing for the element and its children. <div hx-disable>...</div>
hx-preserve Preserves the element (and its state) during a swap, instead of replacing it. <input hx-preserve id="my-input">
hx-sync Controls how requests for the element are synchronized (e.g., drop, abort, queue, replace). <button hx-get="/data" hx-sync="this:queue">Queue Requests</button>
hx-on Allows you to specify inline event handlers for htmx events (e.g., htmx:afterSwap: window.scrollTo(0,0)). <div hx-get="/data" hx-on="htmx:afterSwap: window.scrollTo(0,0)">...</div>
hx-select-oob Allows you to select and swap content "out of band" from the response, targeting elements outside the normal swap target. <div hx-get="/fragment" hx-select-oob="#sidebar">...</div>
hx-replace-url Replaces the current browser URL with the request URL when the request completes, without adding a new history entry. <a hx-get="/page2" hx-replace-url="true">Go to Page 2</a>
hx-history Controls whether a request updates browser history (true, false, or restore). <a hx-get="/page" hx-history="false">No History</a>
hx-history-elt Specifies the element whose content should be saved and restored during history navigation. <div id="main" hx-history-elt>...</div>
hx-vals-js Allows you to specify a JavaScript expression that returns an object to be submitted as parameters. <button hx-post="/vote" hx-vals-js="getVoteParams()">Vote</button>
hx-headers-js Allows you to specify a JavaScript expression that returns an object to be used as request headers. <button hx-get="/data" hx-headers-js="getHeaders()">Get Data</button>
hx-params-js Allows you to specify a JavaScript expression that returns an array of parameter names to submit. <form hx-post="/submit" hx-params-js="getParamNames()">...</form>
hx-encoding-js Allows you to specify a JavaScript expression that returns the encoding type for the request. <form hx-post="/upload" hx-encoding-js="getEncodingType()">...</form>

htmx CSS Classes

htmx applies special CSS classes to elements during the request lifecycle. These classes can be used to style elements based on their current state (e.g., loading, swapping, error).

Class When Applied Description
htmx-request On the element issuing the request Added while an AJAX request is in flight.
htmx-settling On the target element Added while the target element is being updated/swapped.
htmx-swapping On the target element Added while the swap animation is running (if any).
htmx-added On newly added elements Added to elements that are newly added to the DOM by htmx.
htmx-indicator On indicator elements Should be added to elements you want to show/hide as loading indicators. htmx will automatically add/remove htmx-request to these elements as well.
htmx-error On the element issuing the request Added if the request results in an error (e.g., network or server error).
htmx-triggered On the element that triggered the request Added to the element that triggered the request for the duration of the request.

htmx Request Headers

htmx sends a number of HTTP request headers with each AJAX request. These headers can be used by the server to detect and handle htmx requests appropriately.

Header Description Example Value
HX-Request Sent with every htmx request. Set to true to indicate the request was made by htmx. true
HX-Boosted Set to true if the request was initiated via hx-boost (boosted navigation). true or not sent
HX-Current-URL The current URL of the browser when the request was made. https://example.com/page
HX-Target The id of the target element that will be swapped. main-content
HX-Trigger-Name The name of the element that triggered the request, if any. save-btn
HX-Trigger The id of the element that triggered the request, if any. delete-row-1
HX-Trigger-Id The id of the element that triggered the request, if any. (Alias for HX-Trigger in some versions.) delete-row-1
HX-Request Always set to true for htmx requests. true
HX-History-Restore-Request Set to true if the request is being made as part of a history restoration after a back/forward navigation. true or not sent
HX-Prompt If the request was triggered by a prompt (e.g., hx-prompt), this header contains the value entered by the user. Some user input
HX-Triggering-Event If the request was triggered by an event, this header contains a JSON-encoded description of the event. {"type":"click"}

htmx Response Headers

htmx recognizes several HTTP response headers that allow the server to control client-side behavior after an AJAX request. These headers can be used to trigger redirects, refresh the page, push/replace browser history, trigger events, and more.

Header Description Example Value
HX-Redirect Redirects the browser to the specified URL. /login
HX-Refresh If set to true, causes the browser to do a full page reload. true
HX-Location Pushes a new location into the browser's address bar, optionally with a source and event. {"path":"/new-page","source":"#main","event":"show"}
HX-Push-Url Pushes the given URL into the browser history. /new-url
HX-Replace-Url Replaces the current URL in the browser history with the given URL. /replace-url
HX-Reswap Overrides the hx-swap value for this response only. outerHTML
HX-Retarget Overrides the hx-target value for this response only. #other-element
HX-Trigger Triggers the named event(s) on the client after the response is received. Value can be a space-separated list or a JSON object for event detail. customEvent or {"customEvent":{"detail":"value"}}
HX-Trigger-After-Swap Triggers the named event(s) after the swap is complete. afterSwapEvent
HX-Trigger-After-Settle Triggers the named event(s) after settle is complete. afterSettleEvent
HX-Replace-Url Replaces the current URL in the browser history with the given URL. /replace-url
HX-Push-Url Pushes the given URL into the browser history. /new-url
HX-Retarget Overrides the hx-target value for this response only. #other-element
HX-Reswap Overrides the hx-swap value for this response only. outerHTML

htmx Events

htmx emits a variety of custom events during the request and swap lifecycle. You can listen for these events to add custom behavior to your application.

Event When Fired
htmx:configRequest Before an AJAX request is sent. Allows you to modify the request (headers, parameters, etc.).
htmx:beforeRequest Just before an AJAX request is issued.
htmx:send When an AJAX request is sent.
htmx:afterRequest After an AJAX request completes (success or error).
htmx:beforeOnLoad Before the response is handled (before swap).
htmx:beforeSwap Before the swap is performed. Allows you to modify the response or cancel the swap.
htmx:afterSwap After the swap is performed.
htmx:beforeSettle Before the settle phase (after swap, before animations complete).
htmx:afterSettle After the settle phase (after animations complete).
htmx:confirm When a request is about to be issued and hx-confirm is present. Allows you to override the confirmation dialog.
htmx:prompt When a request is about to be issued and hx-prompt is present. Allows you to override the prompt dialog.
htmx:validation:validate When a form is about to be submitted. Allows you to perform custom validation.
htmx:validation:failed When form validation fails.
htmx:validation:halted When form submission is halted due to validation.
htmx:load When new content is loaded into the DOM by htmx.
htmx:historyRestore When a history restoration occurs (back/forward navigation).
htmx:abort When a request is aborted (e.g., due to hx-sync or user action).
htmx:beforeProcessNode Before a newly loaded node is processed by htmx.
htmx:afterProcessNode After a newly loaded node is processed by htmx.
htmx:responseError When a response error occurs (e.g., non-2xx status code).
htmx:sendError When a network error occurs while sending a request.
htmx:timeout When a request times out.
htmx:xhr:progress When an XHR progress event occurs (for file uploads, etc.).
htmx:xhr:loadstart When an XHR loadstart event occurs.
htmx:xhr:loadend When an XHR loadend event occurs.

JavaScript API

htmx exposes a JavaScript API for advanced use cases, allowing you to interact with htmx programmatically.

Method / Property Description Example
htmx.ajax(method, url, target, values, headers) Performs an AJAX request using the specified HTTP method and swaps the response into the target element. htmx.ajax('GET', '/hello', '#result')
htmx.process(element) Processes a DOM element and its children for htmx attributes, activating them. htmx.process(document.getElementById('new-content'))
htmx.on(element, event, handler) Adds an event listener for an htmx event to the specified element. htmx.on(document.body, 'htmx:afterSwap', function(evt) { ... });
htmx.off(element, event, handler) Removes an event listener for an htmx event from the specified element. htmx.off(document.body, 'htmx:afterSwap', handler);
htmx.trigger(element, event, detail) Triggers an htmx event on the specified element, optionally passing event detail. htmx.trigger('#myDiv', 'htmx:afterSwap', {foo: 'bar'});
htmx.find(selector) Finds and returns the first element matching the selector. htmx.find('#myDiv')
htmx.findAll(selector) Finds and returns all elements matching the selector. htmx.findAll('.item')
htmx.logAll() Enables logging of all htmx events to the console (for debugging). htmx.logAll()
htmx.logNone() Disables logging of htmx events to the console. htmx.logNone()
htmx.createEventSource(url) Creates an EventSource object for use with hx-ext="sse" (Server-Sent Events extension). htmx.createEventSource('/events')
htmx.createWebSocket(url) Creates a WebSocket object for use with hx-ext="ws" (WebSocket extension). htmx.createWebSocket('wss://example.com/ws')
htmx.values(element) Returns a JavaScript object containing the values that would be submitted by the element. htmx.values(document.querySelector('form'))
htmx.remove(element, delay) Removes the element from the DOM, optionally after a delay (in milliseconds). htmx.remove('#myDiv', 1000)
htmx.addClass(element, className) Adds a CSS class to the element. htmx.addClass('#myDiv', 'is-active')
htmx.removeClass(element, className) Removes a CSS class from the element. htmx.removeClass('#myDiv', 'is-active')
htmx.toggleClass(element, className) Toggles a CSS class on the element. htmx.toggleClass('#myDiv', 'is-active')
htmx.closest(element, selector) Finds the closest ancestor of the element matching the selector. htmx.closest('#myDiv', '.container')
htmx.defineExtension(name, extension) Defines a new htmx extension. htmx.defineExtension('myExt', { ... });
htmx.removeExtension(name) Removes a previously defined htmx extension. htmx.removeExtension('myExt')
htmx.config The global configuration object for htmx (see Configuration Options section). htmx.config.useTemplateFragments = true
htmx.version The current version of htmx. htmx.version

Configuration Options

htmx can be configured globally via the htmx.config object. These options allow you to customize the behavior of htmx to fit your application's needs.

Option Default Description
historyEnabled true Enable or disable htmx history support.
historyCacheSize 10 The number of pages to cache in the history cache.
refreshOnHistoryMiss false Refresh the page if a history miss occurs.
defaultSwapStyle 'innerHTML' The default swap style to use if hx-swap is not specified.
defaultSettleDelay 20 The default delay (in ms) before the settle phase.
defaultFocusScroll true Scroll the focused element into view after a swap.
includeIndicatorStyles true Include default indicator styles for htmx-indicator elements.
useTemplateFragments false Use <template> fragments for swapping content.
globalViewTransitions false Enable view transitions globally (if supported by the browser).
selfRequestsOnly false Only allow requests to the same origin as the current page.
withCredentials false Send credentials (cookies, HTTP auth) with AJAX requests.
timeout 0 The timeout (in ms) for AJAX requests. 0 means no timeout.
wsReconnectDelay 3000 The delay (in ms) before attempting to reconnect a WebSocket.
allowEval false Allow eval() in hx-on and hx-confirm attributes.
defaultEncoding 'application/x-www-form-urlencoded' The default encoding for AJAX requests.
defaultHeaders {} Default headers to send with every request.
defaultParams {} Default parameters to send with every request.
defaultTrigger 'click' The default event to trigger requests.
defaultIndicatorClass 'htmx-indicator' The default class for loading indicators.
defaultRequestClass 'htmx-request' The default class for elements making requests.
defaultSettleClass 'htmx-settling' The default class for elements during the settle phase.
defaultSwappingClass 'htmx-swapping' The default class for elements during the swap phase.