# api.md
```md
+++
title = "Javascript API"
description = """\
This documentation describes the JavaScript API for htmx, including methods and properties for configuring the \
behavior of htmx, working with CSS classes, AJAX requests, event handling, and DOM manipulation. The API provides \
helper functions primarily intended for extension development and event management."""
+++
While it is not a focus of the library, htmx does provide a small API of helper methods, intended mainly for [extension development](https://htmx.org/extensions) or for working with [events](@/events.md).
The [hyperscript](https://hyperscript.org) project is intended to provide more extensive scripting support
for htmx-based applications.
### Method - `htmx.addClass()` {#addClass}
This method adds a class to the given element.
##### Parameters
* `elt` - the element to add the class to
* `class` - the class to add
or
* `elt` - the element to add the class to
* `class` - the class to add
* `delay` - delay (in milliseconds ) before class is added
##### Example
\`\`\`js
// add the class 'myClass' to the element with the id 'demo'
htmx.addClass(htmx.find('#demo'), 'myClass');
// add the class 'myClass' to the element with the id 'demo' after 1 second
htmx.addClass(htmx.find('#demo'), 'myClass', 1000);
\`\`\`
### Method - `htmx.ajax()` {#ajax}
Issues an htmx-style AJAX request. This method returns a Promise, so a callback can be executed after the content has been inserted into the DOM.
##### Parameters
* `verb` - 'GET', 'POST', etc.
* `path` - the URL path to make the AJAX
* `element` - the element to target (defaults to the `body`)
or
* `verb` - 'GET', 'POST', etc.
* `path` - the URL path to make the AJAX
* `selector` - a selector for the target
or
* `verb` - 'GET', 'POST', etc.
* `path` - the URL path to make the AJAX
* `context` - a context object that contains any of the following
* `source` - the source element of the request, `hx-*` attrs which affect the request will be resolved against that element and its ancestors
* `event` - an event that "triggered" the request
* `handler` - a callback that will handle the response HTML
* `target` - the target to swap the response into
* `swap` - how the response will be swapped in relative to the target
* `values` - values to submit with the request
* `headers` - headers to submit with the request
* `select` - allows you to select the content you want swapped from a response
##### Example
\`\`\`js
// issue a GET to /example and put the response HTML into #myDiv
htmx.ajax('GET', '/example', '#myDiv')
// issue a GET to /example and replace #myDiv with the response
htmx.ajax('GET', '/example', {target:'#myDiv', swap:'outerHTML'})
// execute some code after the content has been inserted into the DOM
htmx.ajax('GET', '/example', '#myDiv').then(() => {
// this code will be executed after the 'htmx:afterOnLoad' event,
// and before the 'htmx:xhr:loadend' event
console.log('Content inserted successfully!');
});
\`\`\`
### Method - `htmx.closest()` {#closest}
Finds the closest matching element in the given elements parentage, inclusive of the element
##### Parameters
* `elt` - the element to find the selector from
* `selector` - the selector to find
##### Example
\`\`\`js
// find the closest enclosing div of the element with the id 'demo'
htmx.closest(htmx.find('#demo'), 'div');
\`\`\`
### Property - `htmx.config` {#config}
A property holding the configuration htmx uses at runtime.
Note that using a [meta tag](@/docs.md#config) is the preferred mechanism for setting these properties.
##### Properties
* `attributesToSettle:["class", "style", "width", "height"]` - array of strings: the attributes to settle during the settling phase
* `refreshOnHistoryMiss:false` - boolean: if set to `true` htmx will issue a full page refresh on history misses rather than use an AJAX request
* `defaultSettleDelay:20` - int: the default delay between completing the content swap and settling attributes
* `defaultSwapDelay:0` - int: the default delay between receiving a response from the server and doing the swap
* `defaultSwapStyle:'innerHTML'` - string: the default swap style to use if [`hx-swap`](@/attributes/hx-swap.md) is omitted
* `historyCacheSize:10` - int: the number of pages to keep in `localStorage` for history support
* `historyEnabled:true` - boolean: whether or not to use history
* `includeIndicatorStyles:true` - boolean: if true, htmx will inject a small amount of CSS into the page to make indicators invisible unless the `htmx-indicator` class is present
* `indicatorClass:'htmx-indicator'` - string: the class to place on indicators when a request is in flight
* `requestClass:'htmx-request'` - string: the class to place on triggering elements when a request is in flight
* `addedClass:'htmx-added'` - string: the class to temporarily place on elements that htmx has added to the DOM
* `settlingClass:'htmx-settling'` - string: the class to place on target elements when htmx is in the settling phase
* `swappingClass:'htmx-swapping'` - string: the class to place on target elements when htmx is in the swapping phase
* `allowEval:true` - boolean: allows the use of eval-like functionality in htmx, to enable `hx-vars`, trigger conditions & script tag evaluation. Can be set to `false` for CSP compatibility.
* `allowScriptTags:true` - boolean: allows script tags to be evaluated in new content
* `inlineScriptNonce:''` - string: the [nonce](https://developer.mozilla.org/docs/Web/HTML/Global_attributes/nonce) to add to inline scripts
* `inlineStyleNonce:''` - string: the [nonce](https://developer.mozilla.org/docs/Web/HTML/Global_attributes/nonce) to add to inline styles
* `withCredentials:false` - boolean: allow cross-site Access-Control requests using credentials such as cookies, authorization headers or TLS client certificates
* `timeout:0` - int: the number of milliseconds a request can take before automatically being terminated
* `wsReconnectDelay:'full-jitter'` - string/function: the default implementation of `getWebSocketReconnectDelay` for reconnecting after unexpected connection loss by the event code `Abnormal Closure`, `Service Restart` or `Try Again Later`
* `wsBinaryType:'blob'` - string: the [the type of binary data](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) being received over the WebSocket connection
* `disableSelector:"[hx-disable], [data-hx-disable]"` - array of strings: htmx will not process elements with this attribute on it or a parent
* `disableInheritance:false` - boolean: If it is set to `true`, the inheritance of attributes is completely disabled and you can explicitly specify the inheritance with the [hx-inherit](@/attributes/hx-inherit.md) attribute.
* `scrollBehavior:'instant'` - string: the scroll behavior when using the [show](@/attributes/hx-swap.md#scrolling-scroll-show) modifier with `hx-swap`. The allowed values are `instant` (scrolling should happen instantly in a single jump), `smooth` (scrolling should animate smoothly) and `auto` (scroll behavior is determined by the computed value of [scroll-behavior](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior)).
* `defaultFocusScroll:false` - boolean: if the focused element should be scrolled into view, can be overridden using the [focus-scroll](@/attributes/hx-swap.md#focus-scroll) swap modifier
* `getCacheBusterParam:false` - boolean: if set to true htmx will append the target element to the `GET` request in the format `org.htmx.cache-buster=targetElementId`
* `globalViewTransitions:false` - boolean: if set to `true`, htmx will use the [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) API when swapping in new content.
* `methodsThatUseUrlParams:["get", "delete"]` - array of strings: htmx will format requests with these methods by encoding their parameters in the URL, not the request body
* `selfRequestsOnly:true` - boolean: whether to only allow AJAX requests to the same domain as the current document
* `ignoreTitle:false` - boolean: if set to `true` htmx will not update the title of the document when a `title` tag is found in new content
* `scrollIntoViewOnBoost:true` - boolean: whether or not the target of a boosted element is scrolled into the viewport. If `hx-target` is omitted on a boosted element, the target defaults to `body`, causing the page to scroll to the top.
* `triggerSpecsCache:null` - object: the cache to store evaluated trigger specifications into, improving parsing performance at the cost of more memory usage. You may define a simple object to use a never-clearing cache, or implement your own system using a [proxy object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy)
* `htmx.config.responseHandling:[...]` - HtmxResponseHandlingConfig[]: the default [Response Handling](@/docs.md#response-handling) behavior for response status codes can be configured here to either swap or error
* `htmx.config.allowNestedOobSwaps:true` - boolean: whether to process OOB swaps on elements that are nested within the main response element. See [Nested OOB Swaps](@/attributes/hx-swap-oob.md#nested-oob-swaps).
##### Example
\`\`\`js
// update the history cache size to 30
htmx.config.historyCacheSize = 30;
\`\`\`
### Property - `htmx.createEventSource` {#createEventSource}
A property used to create new [Server Sent Event](https://github.com/bigskysoftware/htmx-extensions/blob/main/src/sse/README.md) sources. This can be updated
to provide custom SSE setup.
##### Value
* `func(url)` - a function that takes a URL string and returns a new `EventSource`
##### Example
\`\`\`js
// override SSE event sources to not use credentials
htmx.createEventSource = function(url) {
return new EventSource(url, {withCredentials:false});
};
\`\`\`
### Property - `htmx.createWebSocket` {#createWebSocket}
A property used to create new [WebSocket](https://github.com/bigskysoftware/htmx-extensions/blob/main/src/ws/README.md). This can be updated
to provide custom WebSocket setup.
##### Value
* `func(url)` - a function that takes a URL string and returns a new `WebSocket`
##### Example
\`\`\`js
// override WebSocket to use a specific protocol
htmx.createWebSocket = function(url) {
return new WebSocket(url, ['wss']);
};
\`\`\`
### Method - `htmx.defineExtension()` {#defineExtension}
Defines a new htmx [extension](https://htmx.org/extensions).
##### Parameters
* `name` - the extension name
* `ext` - the extension definition
##### Example
\`\`\`js
// defines a silly extension that just logs the name of all events triggered
htmx.defineExtension("silly", {
onEvent : function(name, evt) {
console.log("Event " + name + " was triggered!")
}
});
\`\`\`
### Method - `htmx.find()` {#find}
Finds an element matching the selector
##### Parameters
* `selector` - the selector to match
or
* `elt` - the root element to find the matching element in, inclusive
* `selector` - the selector to match
##### Example
\`\`\`js
// find div with id my-div
var div = htmx.find("#my-div")
// find div with id another-div within that div
var anotherDiv = htmx.find(div, "#another-div")
\`\`\`
### Method - `htmx.findAll()` {#findAll}
Finds all elements matching the selector
##### Parameters
* `selector` - the selector to match
or
* `elt` - the root element to find the matching elements in, inclusive
* `selector` - the selector to match
##### Example
\`\`\`js
// find all divs
var allDivs = htmx.findAll("div")
// find all paragraphs within a given div
var allParagraphsInMyDiv = htmx.findAll(htmx.find("#my-div"), "p")
\`\`\`
### Method - `htmx.logAll()` {#logAll}
Log all htmx events, useful for debugging.
##### Example
\`\`\`js
htmx.logAll();
\`\`\`
### Method - `htmx.logNone()` {#logNone}
Log no htmx events, call this to turn off the debugger if you previously enabled it.
##### Example
\`\`\`js
htmx.logNone();
\`\`\`
### Property - `htmx.logger` {#logger}
The logger htmx uses to log with
##### Value
* `func(elt, eventName, detail)` - a function that takes an element, eventName and event detail and logs it
##### Example
\`\`\`js
htmx.logger = function(elt, event, data) {
if(console) {
console.log("INFO:", event, elt, data);
}
}
\`\`\`
### Method - `htmx.off()` {#off}
Removes an event listener from an element
##### Parameters
* `eventName` - the event name to remove the listener from
* `listener` - the listener to remove
or
* `target` - the element to remove the listener from
* `eventName` - the event name to remove the listener from
* `listener` - the listener to remove
##### Example
\`\`\`js
// remove this click listener from the body
htmx.off("click", myEventListener);
// remove this click listener from the given div
htmx.off("#my-div", "click", myEventListener)
\`\`\`
### Method - `htmx.on()` {#on}
Adds an event listener to an element
##### Parameters
* `eventName` - the event name to add the listener for
* `listener` - the listener to add
* `options` - an [options](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#options) object (or a [useCapture](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#usecapture) boolean) to add to the event listener (optional)
or
* `target` - the element to add the listener to
* `eventName` - the event name to add the listener for
* `listener` - the listener to add
* `options` - an [options](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#options) object (or a [useCapture](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#usecapture) boolean) to add to the event listener (optional)
##### Example
\`\`\`js
// add a click listener to the body
var myEventListener = htmx.on("click", function(evt){ console.log(evt); });
// add a click listener to the given div
var myEventListener = htmx.on("#my-div", "click", function(evt){ console.log(evt); });
// add a click listener to the given div that should only be invoked once
var myEventListener = htmx.on("#my-div", "click", function(evt){ console.log(evt); }, { once: true });
\`\`\`
### Method - `htmx.onLoad()` {#onLoad}
Adds a callback for the `htmx:load` event. This can be used to process new content, for example
initializing the content with a javascript library
##### Parameters
* `callback(elt)` - the callback to call on newly loaded content
##### Example
\`\`\`js
htmx.onLoad(function(elt){
MyLibrary.init(elt);
})
\`\`\`
### Method - `htmx.parseInterval()` {#parseInterval}
Parses an interval string consistent with the way htmx does. Useful for plugins that have timing-related attributes.
Caution: Accepts an int followed by either `s` or `ms`. All other values use `parseFloat`
##### Parameters
* `str` - timing string
##### Example
\`\`\`js
// returns 3000
var milliseconds = htmx.parseInterval("3s");
// returns 3 - Caution
var milliseconds = htmx.parseInterval("3m");
\`\`\`
### Method - `htmx.process()` {#process}
Processes new content, enabling htmx behavior. This can be useful if you have content that is added to the DOM
outside of the normal htmx request cycle but still want htmx attributes to work.
##### Parameters
* `elt` - element to process
##### Example
\`\`\`js
document.body.innerHTML = "
Get it!
"
// process the newly added content
htmx.process(document.body);
\`\`\`
### Method - `htmx.remove()` {#remove}
Removes an element from the DOM
##### Parameters
* `elt` - element to remove
or
* `elt` - element to remove
* `delay` - delay (in milliseconds ) before element is removed
##### Example
\`\`\`js
// removes my-div from the DOM
htmx.remove(htmx.find("#my-div"));
// removes my-div from the DOM after a delay of 2 seconds
htmx.remove(htmx.find("#my-div"), 2000);
\`\`\`
### Method - `htmx.removeClass()` {#removeClass}
Removes a class from the given element
##### Parameters
* `elt` - element to remove the class from
* `class` - the class to remove
or
* `elt` - element to remove the class from
* `class` - the class to remove
* `delay` - delay (in milliseconds ) before class is removed
##### Example
\`\`\`js
// removes .myClass from my-div
htmx.removeClass(htmx.find("#my-div"), "myClass");
// removes .myClass from my-div after 6 seconds
htmx.removeClass(htmx.find("#my-div"), "myClass", 6000);
\`\`\`
### Method - `htmx.removeExtension()` {#removeExtension}
Removes the given extension from htmx
##### Parameters
* `name` - the name of the extension to remove
##### Example
\`\`\`js
htmx.removeExtension("my-extension");
\`\`\`
### Method - `htmx.swap()` {#swap}
Performs swapping (and settling) of HTML content
##### Parameters
* `target` - the HTML element or string selector of swap target
* `content` - string representation of content to be swapped
* `swapSpec` - swapping specification, representing parameters from `hx-swap`
* `swapStyle` (required) - swapping style (`innerHTML`, `outerHTML`, `beforebegin` etc)
* `swapDelay`, `settleDelay` (number) - delays before swapping and settling respectively
* `transition` (bool) - whether to use HTML transitions for swap
* `ignoreTitle` (bool) - disables page title updates
* `head` (string) - specifies `head` tag handling strategy (`merge` or `append`). Leave empty to disable head handling
* `scroll`, `scrollTarget`, `show`, `showTarget`, `focusScroll` - specifies scroll handling after swap
* `swapOptions` - additional *optional* parameters for swapping
* `select` - selector for the content to be swapped (equivalent of `hx-select`)
* `selectOOB` - selector for the content to be swapped out-of-band (equivalent of `hx-select-oob`)
* `eventInfo` - an object to be attached to `htmx:afterSwap` and `htmx:afterSettle` elements
* `anchor` - an anchor element that triggered scroll, will be scrolled into view on settle. Provides simple alternative to full scroll handling
* `contextElement` - DOM element that serves as context to swapping operation. Currently used to find extensions enabled for specific element
* `afterSwapCallback`, `afterSettleCallback` - callback functions called after swap and settle respectively. Take no arguments
##### Example
\`\`\`js
// swap #output element inner HTML with div element with "Swapped!" text
htmx.swap("#output", "
Swapped!
", {swapStyle: 'innerHTML'});
\`\`\`
### Method - `htmx.takeClass()` {#takeClass}
Takes the given class from its siblings, so that among its siblings, only the given element will have the class.
##### Parameters
* `elt` - the element that will take the class
* `class` - the class to take
##### Example
\`\`\`js
// takes the selected class from tab2's siblings
htmx.takeClass(htmx.find("#tab2"), "selected");
\`\`\`
### Method - `htmx.toggleClass()` {#toggleClass}
Toggles the given class on an element
##### Parameters
* `elt` - the element to toggle the class on
* `class` - the class to toggle
##### Example
\`\`\`js
// toggles the selected class on tab2
htmx.toggleClass(htmx.find("#tab2"), "selected");
\`\`\`
### Method - `htmx.trigger()` {#trigger}
Triggers a given event on an element
##### Parameters
* `elt` - the element to trigger the event on
* `name` - the name of the event to trigger
* `detail` - details for the event
##### Example
\`\`\`js
// triggers the myEvent event on #tab2 with the answer 42
htmx.trigger("#tab2", "myEvent", {answer:42});
\`\`\`
### Method - `htmx.values()` {#values}
Returns the input values that would resolve for a given element via the htmx value resolution mechanism
##### Parameters
* `elt` - the element to resolve values on
* `request type` - the request type (e.g. `get` or `post`) non-GET's will include the enclosing form of the element.
Defaults to `post`
##### Example
\`\`\`js
// gets the values associated with this form
var values = htmx.values(htmx.find("#myForm"));
\`\`\`
```
# attributes/hx-boost.md
```md
+++
title = "hx-boost"
description = """\
The hx-boost attribute in htmx enables progressive enhancement by converting standard HTML anchors and forms into \
AJAX requests, maintaining graceful fallback for users without JavaScript while providing modern dynamic page \
updates for those with JavaScript enabled."""
+++
The `hx-boost` attribute allows you to "boost" normal anchors and form tags to use AJAX instead. This
has the [nice fallback](https://en.wikipedia.org/wiki/Progressive_enhancement) that, if the user does not
have javascript enabled, the site will continue to work.
For anchor tags, clicking on the anchor will issue a `GET` request to the url specified in the `href` and
will push the url so that a history entry is created. The target is the `` tag, and the `innerHTML`
swap strategy is used by default. All of these can be modified by using the appropriate attributes, except
the `click` trigger.
For forms the request will be converted into a `GET` or `POST`, based on the method in the `method` attribute
and will be triggered by a `submit`. Again, the target will be the `body` of the page, and the `innerHTML`
swap will be used. The url will _not_ be pushed, however, and no history entry will be created. (You can use the
[hx-push-url](@/attributes/hx-push-url.md) attribute if you want the url to be pushed.)
Here is an example of some boosted links:
\`\`\`html
\`\`\`
These links will issue an ajax `GET` request to the respective URLs and replace the body's inner content with it.
Here is an example of a boosted form:
\`\`\`html
\`\`\`
This form will issue an ajax `POST` to the given URL and replace the body's inner content with it.
## Notes
* `hx-boost` is inherited and can be placed on a parent element
* Only links that are to the same domain and that are not local anchors will be boosted
* All requests are done via AJAX, so keep that in mind when doing things like redirects
* To find out if the request results from a boosted anchor or form, look for [`HX-Boosted`](@/reference.md#request_headers) in the request header
* Selectively disable boost on child elements with `hx-boost="false"`
* Disable the replacement of elements via boost, and their children, with [`hx-preserve="true"`](@/attributes/hx-preserve.md)
```
# attributes/hx-confirm.md
```md
+++
title = "hx-confirm"
description = """\
The hx-confirm attribute in htmx provides a way to add confirmation dialogs before executing requests, allowing \
you to protect users from accidental destructive actions. This documentation explains how to implement confirmation \
prompts and customize their behavior through event handling."""
+++
The `hx-confirm` attribute allows you to confirm an action before issuing a request. This can be useful
in cases where the action is destructive and you want to ensure that the user really wants to do it.
Here is an example:
\`\`\`html
\`\`\`
## Event details
The event triggered by `hx-confirm` contains additional properties in its `detail`:
* triggeringEvent: the event that triggered the original request
* issueRequest(skipConfirmation=false): a callback which can be used to confirm the AJAX request
* question: the value of the `hx-confirm` attribute on the HTML element
## Notes
* `hx-confirm` is inherited and can be placed on a parent element
* `hx-confirm` uses the browser's `window.confirm` by default. You can customize this behavior as shown [in this example](@/examples/confirm.md).
* a boolean `skipConfirmation` can be passed to the `issueRequest` callback; if true (defaults to false), the `window.confirm` will not be called and the AJAX request is issued directly
```
# attributes/hx-delete.md
```md
+++
title = "hx-delete"
description = """\
The hx-delete attribute in htmx will cause an element to issue a DELETE request to the specified URL and swap the \
returned HTML into the DOM using a swap strategy."""
+++
The `hx-delete` attribute will cause an element to issue a `DELETE` to the specified URL and swap
the HTML into the DOM using a swap strategy:
\`\`\`html
\`\`\`
This example will cause the `button` to issue a `DELETE` to `/account` and swap the returned HTML into
the `innerHTML` of the `body`.
## Notes
* `hx-delete` is not inherited
* You can control the target of the swap using the [hx-target](@/attributes/hx-target.md) attribute
* You can control the swap strategy by using the [hx-swap](@/attributes/hx-swap.md) attribute
* You can control what event triggers the request with the [hx-trigger](@/attributes/hx-trigger.md) attribute
* You can control the data submitted with the request in various ways, documented here: [Parameters](@/docs.md#parameters)
* To remove the element following a successful `DELETE`, return a `200` status code with an empty body; if the server responds with a `204`, no swap takes place, documented here: [Requests & Responses](@/docs.md#requests)
```
# attributes/hx-disable.md
```md
+++
title = "hx-disable"
description = "The hx-disable attribute in htmx will disable htmx processing for a given element and all its children."
+++
The `hx-disable` attribute will disable htmx processing for a given element and all its children. This can be
useful as a backup for HTML escaping, when you include user generated content in your site, and you want to
prevent malicious scripting attacks.
The value of the tag is ignored, and it cannot be reversed by any content beneath it.
## Notes
* `hx-disable` is inherited
```
# attributes/hx-disabled-elt.md
```md
+++
title = "hx-disabled-elt"
description = """\
The hx-disabled-elt attribute in htmx allows you to specify elements that will have the `disabled` attribute added \
to them for the duration of the request."""
+++
The `hx-disabled-elt` attribute allows you to specify elements that will have the `disabled` attribute
added to them for the duration of the request. The value of this attribute can be:
* A CSS query selector of the element to disable.
* `this` to disable the element itself
* `closest ` which will find the [closest](https://developer.mozilla.org/docs/Web/API/Element/closest)
ancestor element or itself, that matches the given CSS selector
(e.g. `closest fieldset` will disable the closest to the element `fieldset`).
* `find ` which will find the first child descendant element that matches the given CSS selector
* `next` which resolves to [element.nextElementSibling](https://developer.mozilla.org/docs/Web/API/Element/nextElementSibling)
* `next ` which will scan the DOM forward for the first element that matches the given CSS selector
(e.g. `next button` will disable the closest following sibling `button` element)
* `previous` which resolves to [element.previousElementSibling](https://developer.mozilla.org/docs/Web/API/Element/previousElementSibling)
* `previous ` which will scan the DOM backwards for the first element that matches the given CSS selector.
(e.g. `previous input` will disable the closest previous sibling `input` element)
Here is an example with a button that will disable itself during a request:
\`\`\`html
\`\`\`
When a request is in flight, this will cause the button to be marked with [the `disabled` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/disabled),
which will prevent further clicks from occurring.
The `hx-disabled-elt` attribute also supports specifying multiple CSS selectors separated by commas to disable multiple elements during the request. Here is an example that disables buttons and text input fields of a particular form during the request:
\`\`\`html
\`\`\`
## Notes
* `hx-disabled-elt` is inherited and can be placed on a parent element
[hx-trigger]: https://htmx.org/attributes/hx-trigger/
```
# attributes/hx-disinherit.md
```md
+++
title = "hx-disinherit"
description = """\
The hx-disinherit attribute in htmx lets you control how child elements inherit attributes from their parents. This \
documentation explains how to selectively disable inheritance of specific htmx attributes or all attributes, \
allowing for more granular control over your web application's behavior."""
+++
The default behavior for htmx is to "inherit" many attributes automatically: that is, an attribute such as
[hx-target](@/attributes/hx-target.md) may be placed on a parent element, and all child elements will inherit
that target.
The `hx-disinherit` attribute allows you to control this automatic attribute inheritance. An example scenario is to
allow you to place an `hx-boost` on the `body` element of a page, but overriding that behavior in a specific part
of the page to allow for more specific behaviors.
htmx evaluates attribute inheritance as follows:
* when `hx-disinherit` is set on a parent node
* `hx-disinherit="*"` all attribute inheritance for this element will be disabled
* `hx-disinherit="hx-select hx-get hx-target"` disable inheritance for only one or multiple specified attributes
\`\`\`html
\`\`\`
## Notes
* Read more about [Attribute Inheritance](@/docs.md#inheritance)
```
# attributes/hx-encoding.md
```md
+++
title = "hx-encoding"
description = """\
The hx-encoding attribute in htmx allows you to switch the request encoding from the usual \
`application/x-www-form-urlencoded` encoding to `multipart/form-data`, usually to support file uploads in an AJAX \
request."""
+++
The `hx-encoding` attribute allows you to switch the request encoding from the usual `application/x-www-form-urlencoded`
encoding to `multipart/form-data`, usually to support file uploads in an ajax request.
The value of this attribute should be `multipart/form-data`.
The `hx-encoding` tag may be placed on parent elements.
## Notes
* `hx-encoding` is inherited and can be placed on a parent element
```
# attributes/hx-ext.md
```md
+++
title = "hx-ext"
description = """\
The hx-ext attribute in htmx enables one or more htmx extensions for an element and all its children. You can also \
use this attribute to ignore an extension that is enabled by a parent element."""
+++
The `hx-ext` attribute enables an htmx [extension](https://htmx.org/extensions) for an element and all its children.
The value can be a single extension name or a comma-separated list of extensions to apply.
The `hx-ext` tag may be placed on parent elements if you want a plugin to apply to an entire swath of the DOM,
and on the `body` tag for it to apply to all htmx requests.
## Notes
* `hx-ext` is both inherited and merged with parent elements, so you can specify extensions on any element in the DOM
hierarchy and it will apply to all child elements.
* You can ignore an extension that is defined by a parent node using `hx-ext="ignore:extensionName"`
\`\`\`html
"Example" extension is used in this part of the tree...
... but it will not be used in this part.
\`\`\`
\`\`\`html
"preload" and "morph" extensions are used in this part of the tree...
\`\`\`
```
# attributes/hx-get.md
```md
+++
title = "hx-get"
description = """\
The hx-get attribute in htmx will cause an element to issue a GET request to the specified URL and swap the returned \
HTML into the DOM using a swap strategy."""
+++
The `hx-get` attribute will cause an element to issue a `GET` to the specified URL and swap
the HTML into the DOM using a swap strategy:
\`\`\`html
\`\`\`
This example will cause the `button` to issue a `GET` to `/example` and swap the returned HTML into
the `innerHTML` of the `button`.
### Notes
* `hx-get` is not inherited
* By default `hx-get` usually does not include any parameters. You can use the [hx-params](@/attributes/hx-params.md)
attribute to change this
* NB: If the element with the `hx-get` attribute also has a value, this will be included as a parameter unless explicitly removed
* You can control the target of the swap using the [hx-target](@/attributes/hx-target.md) attribute
* You can control the swap strategy by using the [hx-swap](@/attributes/hx-swap.md) attribute
* You can control what event triggers the request with the [hx-trigger](@/attributes/hx-trigger.md) attribute
* You can control the data submitted with the request in various ways, documented here: [Parameters](@/docs.md#parameters)
* An empty `hx-get:""` will make a get request to the current url and will swap the current HTML page
```
# attributes/hx-headers.md
```md
+++
title = "hx-headers"
description = """\
The hx-headers attribute in htmx allows you to add to the headers that will be submitted with an AJAX request."""
+++
The `hx-headers` attribute allows you to add to the headers that will be submitted with an AJAX request.
By default, the value of this attribute is a list of name-expression values in [JSON (JavaScript Object Notation)](https://www.json.org/json-en.html)
format.
If you wish for `hx-headers` to *evaluate* the values given, you can prefix the values with `javascript:` or `js:`.
\`\`\`html
Get Some HTML, Including A Custom Header in the Request
Get Some HTML, Including a Dynamic Custom Header from Javascript in the Request
\`\`\`
## Security Considerations
* By default, the value of `hx-headers` must be valid [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON).
It is **not** dynamically computed. If you use the `javascript:` prefix, be aware that you are introducing
security considerations, especially when dealing with user input such as query strings or user-generated content,
which could introduce a [Cross-Site Scripting (XSS)](https://owasp.org/www-community/attacks/xss/) vulnerability.
* Whilst far from being a foolproof solution to [Cross-Site Request Forgery](https://owasp.org/www-community/attacks/csrf), the `hx-headers` attribute can support backend services to provide [CSRF prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html). For more information see the [CSRF Prevention](https://htmx.org/docs/#csrf-prevention) section.
## Notes
* `hx-headers` is inherited and can be placed on a parent element.
* A child declaration of a header overrides a parent declaration.
```
# attributes/hx-history-elt.md
```md
+++
title = "hx-history-elt"
description = """\
The hx-history-elt attribute in htmx allows you to specify the element that will be used to snapshot and restore \
page state during navigation. In most cases we do not recommend using this element."""
+++
The `hx-history-elt` attribute allows you to specify the element that will be used to snapshot and
restore page state during navigation. By default, the `body` tag is used. This is typically
good enough for most setups, but you may want to narrow it down to a child element. Just make
sure that the element is always visible in your application, or htmx will not be able to restore
history navigation properly.
Here is an example:
\`\`\`html
...
\`\`\`
## Notes
* `hx-history-elt` is not inherited
* In most cases we don't recommend narrowing the history snapshot
```
# attributes/hx-history.md
```md
+++
title = "hx-history"
description = """\
The hx-history attribute in htmx allows you to prevent sensitive page data from being stored in the browser's \
localStorage cache during history navigation, ensuring that the page state is retrieved from the server instead when \
navigating through history."""
+++
Set the `hx-history` attribute to `false` on any element in the current document, or any html fragment loaded into the current document by htmx, to prevent sensitive data being saved to the localStorage cache when htmx takes a snapshot of the page state.
History navigation will work as expected, but on restoration the URL will be requested from the server instead of the history cache.
Here is an example:
\`\`\`html
...
\`\`\`
## Notes
* `hx-history="false"` can be present *anywhere* in the document to embargo the current page state from the history cache (i.e. even outside the element specified for the history snapshot [hx-history-elt](@/attributes/hx-history-elt.md)).
```
# attributes/hx-include.md
```md
+++
title = "hx-include"
description = "The hx-include attribute in htmx allows you to include additional element values in an AJAX request."
+++
The `hx-include` attribute allows you to include additional element values in an AJAX request. The value of this
attribute can be:
* A CSS query selector of the elements to include.
* `this` which will include the descendants of the element.
* `closest ` which will find the [closest](https://developer.mozilla.org/docs/Web/API/Element/closest)
ancestor element or itself, that matches the given CSS selector
(e.g. `closest tr` will target the closest table row to the element).
* `find ` which will find the first child descendant element that matches the given CSS selector.
* `next ` which will scan the DOM forward for the first element that matches the given CSS selector.
(e.g. `next .error` will target the closest following sibling element with `error` class)
* `previous ` which will scan the DOM backwards for the first element that matches the given CSS selector.
(e.g. `previous .error` will target the closest previous sibling with `error` class)
Here is an example that includes a separate input value:
\`\`\`html
Enter email:
\`\`\`
This is a little contrived as you would typically enclose both of these elements in a `form` and submit
the value automatically, but it demonstrates the concept.
Note that if you include a non-input element, all input elements enclosed in that element will be included.
## Notes
* `hx-include` is inherited and can be placed on a parent element
* While `hx-include` is inherited, it is evaluated from the element triggering the request. It is easy to get confused
when working with the extended selectors such as `find` and `closest`.
\`\`\`html
Enter email:
\`\`\`
In the above example, when clicking on the button, the `find input` selector is resolved from the button itself, which
does not return any element here, since the button doesn't have any `input` child, thus in this case, raises an error.
* A standard CSS selector resolves
to [document.querySelectorAll](https://developer.mozilla.org/docs/Web/API/Document/querySelectorAll) and will include
multiple elements, while the extended selectors such as `find` or `next` only return a single element at most to
include
* `hx-include` will ignore disabled inputs
```
# attributes/hx-indicator.md
```md
+++
title = "hx-indicator"
description = """\
The hx-indicator attribute in htmx allows you to specify the element that will have the `htmx-request` class added \
to it for the duration of the request. This can be used to show spinners or progress indicators while the request is \
in flight."""
+++
The `hx-indicator` attribute allows you to specify the element that will have the `htmx-request` class
added to it for the duration of the request. This can be used to show spinners or progress indicators
while the request is in flight.
The value of this attribute is a CSS query selector of the element or elements to apply the class to,
or the keyword [`closest`](https://developer.mozilla.org/docs/Web/API/Element/closest), followed by a CSS selector,
which will find the closest ancestor element or itself, that matches the given CSS selector (e.g. `closest tr`);
Here is an example with a spinner adjacent to the button:
\`\`\`html
\`\`\`
When a request is in flight, this will cause the `htmx-request` class to be added to the `#spinner`
image. The image also has the `htmx-indicator` class on it, which defines an opacity transition
that will show the spinner:
\`\`\`css
.htmx-indicator{
opacity:0;
transition: opacity 500ms ease-in;
}
.htmx-request .htmx-indicator{
opacity:1;
}
.htmx-request.htmx-indicator{
opacity:1;
}
\`\`\`
If you would prefer a different effect for showing the spinner you could define and use your own indicator
CSS. Here is an example that uses `display` rather than opacity (Note that we use `my-indicator` instead of `htmx-indicator`):
\`\`\`css
.my-indicator{
display:none;
}
.htmx-request .my-indicator{
display:inline;
}
.htmx-request.my-indicator{
display:inline;
}
\`\`\`
Note that the target of the `hx-indicator` selector need not be the exact element that you
want to show: it can be any element in the parent hierarchy of the indicator.
Finally, note that the `htmx-request` class by default is added to the element causing
the request, so you can place an indicator inside of that element and not need to explicitly
call it out with the `hx-indicator` attribute:
\`\`\`html
\`\`\`
## Demo
This simulates what a spinner might look like in that situation:
## Notes
* `hx-indicator` is inherited and can be placed on a parent element
* In the absence of an explicit indicator, the `htmx-request` class will be added to the element triggering the
request
* If you want to use your own CSS but still use `htmx-indicator` as class name, then you need to disable `includeIndicatorStyles`. See [Configuring htmx](@/docs.md#config). The easiest way is to add this to the `` of your HTML:
\`\`\`html
\`\`\`
```
# attributes/hx-inherit.md
```md
+++
title = "hx-inherit"
description = """\
The hx-inherit attribute in htmx allows you to explicitly control attribute inheritance behavior between parent and \
child elements, providing fine-grained control over which htmx attributes are inherited when the default inheritance \
system is disabled through configuration."""
+++
The default behavior for htmx is to "inherit" many attributes automatically: that is, an attribute such as
[hx-target](@/attributes/hx-target.md) may be placed on a parent element, and all child elements will inherit
that target. Some people do not like this feature and instead prefer to explicitly specify inheritance for attributes.
To support this mode of development, htmx offers the `htmx.config.disableInheritance` setting, which can be set to
`true` to prevent inheritance from being the default behavior for any of the htmx attributes.
The `hx-inherit` attribute allows you to control the inheritance of attributes manually.
htmx evaluates attribute inheritance as follows:
* when `hx-inherit` is set on a parent node
* `inherit="*"` all attribute inheritance for this element will be enabled
* `hx-inherit="hx-select hx-get hx-target"` enable inheritance for only one or multiple specified attributes
Here is an example of a div that shares an `hx-target` attribute for a set of anchor tags when `htmx.config.disableInheritance`
is set to false:
\`\`\`html
\`\`\`
## Notes
* Read more about [Attribute Inheritance](@/docs.md#inheritance)
```
# attributes/hx-on.md
```md
+++
title = "hx-on"
description = """\
The hx-on attributes in htmx allow you to write inline JavaScript event handlers directly on HTML elements, \
supporting both standard DOM events and htmx-specific events with improved locality of behavior."""
+++
The `hx-on*` attributes allow you to embed scripts inline to respond to events directly on an element; similar to the
[`onevent` properties](https://developer.mozilla.org/en-US/docs/Web/Events/Event_handlers#using_onevent_properties) found in HTML, such as `onClick`.
The `hx-on*` attributes improve upon `onevent` by enabling the handling of any arbitrary JavaScript event,
for enhanced [Locality of Behaviour (LoB)](/essays/locality-of-behaviour/) even when dealing with non-standard DOM events. For example, these
attributes allow you to handle [htmx events](/reference#events).
With `hx-on` attributes, you specify the event name as part of the attribute name, after a colon. So, for example, if
you want to respond to a `click` event, you would use the attribute `hx-on:click`:
\`\`\`html
Click
\`\`\`
Note that this syntax can be used to capture all htmx events, as well as most other custom events, in addition to the
standard DOM events.
One gotcha to note is that DOM attributes do not preserve case. This means, unfortunately, an attribute like
`hx-on:htmx:beforeRequest` **will not work**, because the DOM lowercases the attribute names. Fortunately, htmx supports
both camel case event names and also [kebab-case event names](@/docs.md#events), so you can use `hx-on:htmx:before-request` instead.
In order to make writing htmx-based event handlers a little easier, you can use the shorthand double-colon `hx-on::` for htmx
events, and omit the "htmx" part:
\`\`\`html
\`\`\`
If you wish to handle multiple different events, you can simply add multiple attributes to an element:
\`\`\`html
\`\`\`
Finally, in order to make this feature compatible with some templating languages (e.g. [JSX](https://react.dev/learn/writing-markup-with-jsx)) that do not like having a colon (`:`)
in HTML attributes, you may use dashes in the place of colons for both the long form and the shorthand form:
\`\`\`html
\`\`\`
### hx-on (deprecated)
The value is an event name, followed by a colon `:`, followed by the script:
\`\`\`html
\`\`\`
Multiple handlers can be defined by putting them on new lines:
\`\`\`html
\`\`\`
### Symbols
Like `onevent`, two symbols are made available to event handler scripts:
* `this` - The element on which the `hx-on` attribute is defined
* `event` - The event that triggered the handler
### Notes
* `hx-on` is _not_ inherited, however due to
[event bubbling](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture),
`hx-on` attributes on parent elements will typically be triggered by events on child elements
* `hx-on:*` and `hx-on` cannot be used together on the same element; if `hx-on:*` is present, the value of an `hx-on` attribute
on the same element will be ignored. The two forms can be mixed in the same document, however.
```
# attributes/hx-params.md
```md
+++
title = "hx-params"
description = """\
The hx-params attribute in htmx allows you to filter the parameters that will be submitted with an AJAX request."""
+++
The `hx-params` attribute allows you to filter the parameters that will be submitted with an AJAX request.
The possible values of this attribute are:
* `*` - Include all parameters (default)
* `none` - Include no parameters
* `not ` - Include all except the comma separated list of parameter names
* `` - Include all the comma separated list of parameter names
\`\`\`html
Get Some HTML, Including Params
\`\`\`
This div will include all the parameters that a `POST` would, but they will be URL encoded
and included in the URL, as per usual with a `GET`.
## Notes
* `hx-params` is inherited and can be placed on a parent element
```
# attributes/hx-patch.md
```md
+++
title = "hx-patch"
description = """\
The hx-patch attribute in htmx will cause an element to issue a PATCH request to the specified URL and swap the \
returned HTML into the DOM using a swap strategy."""
+++
The `hx-patch` attribute will cause an element to issue a `PATCH` to the specified URL and swap
the HTML into the DOM using a swap strategy:
\`\`\`html
\`\`\`
This example will cause the `button` to issue a `PATCH` to `/account` and swap the returned HTML into
the `innerHTML` of the `body`.
## Notes
* `hx-patch` is not inherited
* You can control the target of the swap using the [hx-target](@/attributes/hx-target.md) attribute
* You can control the swap strategy by using the [hx-swap](@/attributes/hx-swap.md) attribute
* You can control what event triggers the request with the [hx-trigger](@/attributes/hx-trigger.md) attribute
* You can control the data submitted with the request in various ways, documented here: [Parameters](@/docs.md#parameters)
```
# attributes/hx-post.md
```md
+++
title = "hx-post"
description = """\
The hx-post attribute in htmx will cause an element to issue a POST request to the specified URL and swap the \
returned HTML into the DOM using a swap strategy."""
+++
The `hx-post` attribute will cause an element to issue a `POST` to the specified URL and swap
the HTML into the DOM using a swap strategy:
\`\`\`html
\`\`\`
This example will cause the `button` to issue a `POST` to `/account/enable` and swap the returned HTML into
the `innerHTML` of the `body`.
## Notes
* `hx-post` is not inherited
* You can control the target of the swap using the [hx-target](@/attributes/hx-target.md) attribute
* You can control the swap strategy by using the [hx-swap](@/attributes/hx-swap.md) attribute
* You can control what event triggers the request with the [hx-trigger](@/attributes/hx-trigger.md) attribute
* You can control the data submitted with the request in various ways, documented here: [Parameters](@/docs.md#parameters)
```
# attributes/hx-preserve.md
```md
+++
title = "hx-preserve"
description = """\
The hx-preserve attribute in htmx allows you to keep an element unchanged during HTML replacement. Elements with \
hx-preserve set are preserved by `id` when htmx updates any ancestor element."""
+++
The `hx-preserve` attribute allows you to keep an element unchanged during HTML replacement.
Elements with `hx-preserve` set are preserved by `id` when htmx updates any ancestor element.
You *must* set an unchanging `id` on elements for `hx-preserve` to work.
The response requires an element with the same `id`, but its type and other attributes are ignored.
## Notes
* `hx-preserve` is not inherited
* You can use `hx-preserve="true"` or use it as a boolean attribute with just `hx-preserve`
* Some elements cannot unfortunately be preserved properly, such as `` (focus and caret position are lost), iframes or certain types of videos. To tackle some of these cases we recommend the [morphdom extension](https://github.com/bigskysoftware/htmx-extensions/blob/main/src/morphdom-swap/README.md), which does a more elaborate DOM
reconciliation
* When using [History Support](@/docs.md#history) for actions like the back button `hx-preserve` elements will also have their state preserved
* Avoid using [hx-swap](@/attributes/hx-swap.md) set to `none` with requests that could contain a `hx-preserve` element to avoid losing it
* `hx-preserve` can cause elements to be removed from their current location and relocated to a new location when swapping in a partial/oob response
\`\`\`html
Just relocated the video here
\`\`\`
* Can be used on the inside content of a [hx-swap-oob](@/attributes/hx-swap-oob.md) element
\`\`\`html
Notification updated but keep the same retain
\`\`\`
```
# attributes/hx-prompt.md
```md
+++
title = "hx-prompt"
description = """\
The hx-prompt attribute in htmx allows you to show a prompt before issuing a request. The value of the prompt will \
be included in the request in the `HX-Prompt` header."""
+++
The `hx-prompt` attribute allows you to show a prompt before issuing a request. The value of
the prompt will be included in the request in the `HX-Prompt` header.
Here is an example:
\`\`\`html
\`\`\`
## Notes
* `hx-prompt` is inherited and can be placed on a parent element
```
# attributes/hx-push-url.md
```md
+++
title = "hx-push-url"
description = """\
The hx-push-url attribute in htmx allows you to push a URL into the browser location history. This creates a new \
history entry, allowing navigation with the browser's back and forward buttons."""
+++
The `hx-push-url` attribute allows you to push a URL into the browser [location history](https://developer.mozilla.org/en-US/docs/Web/API/History_API).
This creates a new history entry, allowing navigation with the browser’s back and forward buttons.
htmx snapshots the current DOM and saves it into its history cache, and restores from this cache on navigation.
The possible values of this attribute are:
1. `true`, which pushes the fetched URL into history.
2. `false`, which disables pushing the fetched URL if it would otherwise be pushed due to inheritance or [`hx-boost`](/attributes/hx-boost).
3. A URL to be pushed into the location bar.
This may be relative or absolute, as per [`history.pushState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState).
Here is an example:
\`\`\`html
Go to My Account
\`\`\`
This will cause htmx to snapshot the current DOM to `localStorage` and push the URL `/account' into the browser location bar.
Another example:
\`\`\`html
Go to My Account
\`\`\`
This will push the URL `/account/home' into the location history.
## Notes
* `hx-push-url` is inherited and can be placed on a parent element
* The [`HX-Push-Url` response header](@/headers/hx-push-url.md) has similar behavior and can override this attribute.
* The [`hx-history-elt` attribute](@/attributes/hx-history-elt.md) allows changing which element is saved in the history cache.
```
# attributes/hx-put.md
```md
+++
title = "hx-put"
description = """\
The hx-put attribute in htmx will cause an element to issue a PUT request to the specified URL and swap the returned \
HTML into the DOM using a swap strategy."""
+++
The `hx-put` attribute will cause an element to issue a `PUT` to the specified URL and swap
the HTML into the DOM using a swap strategy:
\`\`\`html
\`\`\`
This example will cause the `button` to issue a `PUT` to `/account` and swap the returned HTML into
the `innerHTML` of the `body`.
## Notes
* `hx-put` is not inherited
* You can control the target of the swap using the [hx-target](@/attributes/hx-target.md) attribute
* You can control the swap strategy by using the [hx-swap](@/attributes/hx-swap.md) attribute
* You can control what event triggers the request with the [hx-trigger](@/attributes/hx-trigger.md) attribute
* You can control the data submitted with the request in various ways, documented here: [Parameters](@/docs.md#parameters)
```
# attributes/hx-replace-url.md
```md
+++
title = "hx-replace-url"
description = """\
The hx-replace-url attribute in htmx allows you to replace the current URL of the browser location history."""
+++
The `hx-replace-url` attribute allows you to replace the current url of the browser [location history](https://developer.mozilla.org/en-US/docs/Web/API/History_API).
The possible values of this attribute are:
1. `true`, which replaces the fetched URL in the browser navigation bar.
2. `false`, which disables replacing the fetched URL if it would otherwise be replaced due to inheritance.
3. A URL to be replaced into the location bar.
This may be relative or absolute, as per [`history.replaceState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState).
Here is an example:
\`\`\`html
Go to My Account
\`\`\`
This will cause htmx to snapshot the current DOM to `localStorage` and replace the URL `/account' in the browser location bar.
Another example:
\`\`\`html
Go to My Account
\`\`\`
This will replace the URL `/account/home' in the browser location bar.
## Notes
* `hx-replace-url` is inherited and can be placed on a parent element
* The [`HX-Replace-Url` response header](@/headers/hx-replace-url.md) has similar behavior and can override this attribute.
* The [`hx-history-elt` attribute](@/attributes/hx-history-elt.md) allows changing which element is saved in the history cache.
* The [`hx-push-url` attribute](@/attributes/hx-push-url.md) is a similar and more commonly used attribute, which creates a
new history entry rather than replacing the current one.
```
# attributes/hx-request.md
```md
+++
title = "hx-request"
description = """\
The hx-request attribute in htmx allows you to configure the request timeout, whether the request will send \
credentials, and whether the request will include headers."""
+++
The `hx-request` attribute allows you to configure various aspects of the request via the following attributes:
* `timeout` - the timeout for the request, in milliseconds
* `credentials` - if the request will send credentials
* `noHeaders` - strips all headers from the request
These attributes are set using a JSON-like syntax:
\`\`\`html
...
\`\`\`
You may make the values dynamically evaluated by adding the `javascript:` or `js:` prefix:
\`\`\`html
...
\`\`\`
## Notes
* `hx-request` is merge-inherited and can be placed on a parent element
```
# attributes/hx-select-oob.md
```md
+++
title = "hx-select-oob"
description = """\
The hx-select-oob attribute in htmx allows you to select content from a response to be swapped in via an out-of-band \
swap. The value of this attribute is comma separated list of elements to be swapped out of band."""
+++
The `hx-select-oob` attribute allows you to select content from a response to be swapped in via an out-of-band swap.
The value of this attribute is comma separated list of elements to be swapped out of band. This attribute is almost
always paired with [hx-select](@/attributes/hx-select.md).
Here is an example that selects a subset of the response content:
\`\`\`html
\`\`\`
This button will issue a `GET` to `/info` and then select the element with the id `info-details`,
which will replace the entire button in the DOM, and, in addition, pick out an element with the id `alert`
in the response and swap it in for div in the DOM with the same ID.
Each value in the comma separated list of values can specify any valid [`hx-swap`](@/attributes/hx-swap.md)
strategy by separating the selector and the swap strategy with a `:`, with the strategy otherwise defaulting to `outerHTML`.
For example, to prepend the alert content instead of replacing it:
\`\`\`html
\`\`\`
## Notes
* `hx-select-oob` is inherited and can be placed on a parent element
```
# attributes/hx-select.md
```md
+++
title = "hx-select"
description = "The hx-select attribute in htmx allows you to select the content you want swapped from a response."
+++
The `hx-select` attribute allows you to select the content you want swapped from a response. The value of
this attribute is a CSS query selector of the element or elements to select from the response.
Here is an example that selects a subset of the response content:
\`\`\`html
\`\`\`
So this button will issue a `GET` to `/info` and then select the element with the id `info-detail`,
which will replace the entire button in the DOM.
## Notes
* `hx-select` is inherited and can be placed on a parent element
```
# attributes/hx-swap-oob.md
```md
+++
title = "hx-swap-oob"
description = """\
The hx-swap-oob attribute in htmx allows you to specify that some content in a response should be swapped into the \
DOM somewhere other than the target, that is 'out-of-band'. This allows you to piggyback updates to other elements \
on a response."""
+++
The `hx-swap-oob` attribute allows you to specify that some content in a response should be
swapped into the DOM somewhere other than the target, that is "Out of Band". This allows you to piggyback updates to other element updates on a response.
Consider the following response HTML:
\`\`\`html
...
Saved!
\`\`\`
The first div will be swapped into the target the usual manner. The second div, however, will be swapped in as a replacement for the element with the id `alerts`, and will not end up in the target.
The value of the `hx-swap-oob` can be:
* `true`
* any valid [`hx-swap`](@/attributes/hx-swap.md) value
* any valid [`hx-swap`](@/attributes/hx-swap.md) value, followed by a colon, followed by a CSS selector
If the value is `true` or `outerHTML` (which are equivalent) the element will be swapped inline.
If a swap value is given, that swap strategy will be used and the encapsulating tag pair will be stripped for all strategies other than `outerHTML`.
If a selector is given, all elements matched by that selector will be swapped. If not, the element with an ID matching the new content will be swapped.
### Using alternate swap strategies
As mentioned previously when using swap strategies other than `true` or `outerHTML` the encapsulating tags are stripped, as such you need to excapsulate the returned data with the correct tags for the context.
When trying to insert a `
` in a table that uses `
`:
\`\`\`html
...
\`\`\`
A "plain" table:
\`\`\`html
...
\`\`\`
A `
` may be encapsulated in `
`, ``, `
` or ``, for example:
\`\`\`html
...
\`\`\`
A `
` can be encapsulated in `
` or ``:
\`\`\`html
...
\`\`\`
### Troublesome Tables and lists
Note that you can use a `template` tag to encapsulate types of elements that, by the HTML spec, can't stand on their own in the
DOM (`
`, `
`, `
`, ``, `
`, ``, `
`, `
`, `
` & `
`).
Here is an example with an out-of-band swap of a table row being encapsulated in this way:
\`\`\`html
...
...
\`\`\`
Note that these template tags will be removed from the final content of the page.
### Slippery SVGs
Some element types, like SVG, use a specific XML namespace for their child elements. This prevents internal elements from working correctly when swapped in, unless they are encapsulated within a `svg` tag. To modify the internal contents of an existing SVG, you can use both `template` and `svg` tags to encapsulate the elements, allowing them to get the correct namespace applied.
Here is an example with an out-of-band swap of svg elements being encapsulated in this way:
\`\`\`html
...
\`\`\`
This will replace circle1 inline and then insert circle2 before circle1.
Note that these `template` and `svg` wrapping tags will be removed from the final content of the page.
## Nested OOB Swaps
By default, any element with `hx-swap-oob=` attribute anywhere in the response is processed for oob swap behavior, including when an element is nested within the main response element.
This can be problematic when using [template fragments](https://htmx.org/essays/template-fragments/) where a fragment may be reused as an oob-swap target and also as part of a bigger fragment. When the bigger fragment is the main response the inner fragment will still be processed as an oob swap, removing it from the dom.
This behavior can be changed by setting the config `htmx.config.allowNestedOobSwaps` to `false`. If this config option is `false`, OOB swaps are only processed when the element is *adjacent to* the main response element, OOB swaps elsewhere will be ignored and oob-swap-related attributes stripped.
## Notes
* `hx-swap-oob` is not inherited
```
# attributes/hx-swap.md
```md
+++
title = "hx-swap"
description = """\
The hx-swap attribute in htmx allows you to specify the 'swap strategy', or how the response will be swapped in \
relative to the target of an AJAX request. The default swap strategy is `innerHTML`."""
+++
The `hx-swap` attribute allows you to specify how the response will be swapped in relative to the
[target](@/attributes/hx-target.md) of an AJAX request. If you do not specify the option, the default is
`htmx.config.defaultSwapStyle` (`innerHTML`).
The possible values of this attribute are:
* `innerHTML` - Replace the inner html of the target element
* `outerHTML` - Replace the entire target element with the response
* `textContent` - Replace the text content of the target element, without parsing the response as HTML
* `beforebegin` - Insert the response before the target element
* `afterbegin` - Insert the response before the first child of the target element
* `beforeend` - Insert the response after the last child of the target element
* `afterend` - Insert the response after the target element
* `delete` - Deletes the target element regardless of the response
* `none`- Does not append content from response (out of band items will still be processed).
These options are based on standard DOM naming and the
[`Element.insertAdjacentHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML)
specification.
So in this code:
\`\`\`html
Get Some HTML & Append It
\`\`\`
The `div` will issue a request to `/example` and append the returned content after the `div`
### Modifiers
The `hx-swap` attributes supports modifiers for changing the behavior of the swap. They are outlined below.
#### Transition: `transition`
If you want to use the new [View Transitions](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) API
when a swap occurs, you can use the `transition:true` option for your swap. You can also enable this feature globally by
setting the `htmx.config.globalViewTransitions` config setting to `true`.
#### Timing: `swap` & `settle`
You can modify the amount of time that htmx will wait after receiving a response to swap the content
by including a `swap` modifier:
\`\`\`html
Get Some HTML & Append It
\`\`\`
Similarly, you can modify the time between the swap and the settle logic by including a `settle`
modifier:
\`\`\`html
Get Some HTML & Append It
\`\`\`
These attributes can be used to synchronize htmx with the timing of CSS transition effects.
#### Title: `ignoreTitle`
By default, htmx will update the title of the page if it finds a `` tag in the response content. You can turn
off this behavior by setting the `ignoreTitle` option to true.
#### Scrolling: `scroll` & `show`
You can also change the scrolling behavior of the target element by using the `scroll` and `show` modifiers, both
of which take the values `top` and `bottom`:
\`\`\`html
Get Some HTML & Append It & Scroll To Bottom
\`\`\`
\`\`\`html
Get Some Content
\`\`\`
If you wish to target a different element for scrolling or showing, you may place a CSS selector after the `scroll:`
or `show:`, followed by `:top` or `:bottom`:
\`\`\`html
Get Some Content
\`\`\`
You may also use `window:top` and `window:bottom` to scroll to the top and bottom of the current window.
\`\`\`html
Get Some Content
\`\`\`
For boosted links and forms the default behaviour is `show:top`. You can disable it globally with
[htmx.config.scrollIntoViewOnBoost](@/api.md#config) or you can use `hx-swap="show:none"` on an element basis.
\`\`\`html
\`\`\`
#### Focus scroll
htmx preserves focus between requests for inputs that have a defined id attribute. By default htmx prevents auto-scrolling to focused inputs between requests which can be unwanted behavior on longer requests when the user has already scrolled away. To enable focus scroll you can use `focus-scroll:true`.
\`\`\`html
\`\`\`
Alternatively, if you want the page to automatically scroll to the focused element after each request you can change the htmx global configuration value `htmx.config.defaultFocusScroll` to true. Then disable it for specific requests using `focus-scroll:false`.
\`\`\`html
\`\`\`
## Notes
* `hx-swap` is inherited and can be placed on a parent element
* The default value of this attribute is `innerHTML`
* Due to DOM limitations, it’s not possible to use the `outerHTML` method on the `` element.
htmx will change `outerHTML` on `` to use `innerHTML`.
* The default swap delay is 0ms
* The default settle delay is 20ms
```
# attributes/hx-sync.md
```md
+++
title = "hx-sync"
description = "The hx-sync attribute in htmx allows you to synchronize AJAX requests between multiple elements."
+++
The `hx-sync` attribute allows you to synchronize AJAX requests between multiple elements.
The `hx-sync` attribute consists of a CSS selector to indicate the element to synchronize on, followed optionally
by a colon and then by an optional syncing strategy. The available strategies are:
* `drop` - drop (ignore) this request if an existing request is in flight (the default)
* `abort` - drop (ignore) this request if an existing request is in flight, and, if that is not the case,
*abort* this request if another request occurs while it is still in flight
* `replace` - abort the current request, if any, and replace it with this request
* `queue` - place this request in the request queue associated with the given element
The `queue` modifier can take an additional argument indicating exactly how to queue:
* `queue first` - queue the first request to show up while a request is in flight
* `queue last` - queue the last request to show up while a request is in flight
* `queue all` - queue all requests that show up while a request is in flight
## Notes
* `hx-sync` is inherited and can be placed on a parent element
This example resolves a race condition between a form's submit request and an individual input's validation request. Normally, without using `hx-sync`, filling out the input and immediately submitting the form triggers two parallel requests to `/validate` and `/store`. Using `hx-sync="closest form:abort"` on the input will watch for requests on the form and abort the input's request if a form request is present or starts while the input request is in flight.
\`\`\`html
\`\`\`
If you'd rather prioritize the validation request over the submit request, you can use the `drop` strategy. This example will prioritize the validation request over the submit request so that if a validation request is in flight, the form cannot be submitted.
\`\`\`html
\`\`\`
When dealing with forms that contain many inputs, you can prioritize the submit request over all input validation requests using the hx-sync `replace` strategy on the form tag. This will cancel any in-flight validation requests and issue only the `hx-post="/store"` request. If you'd rather abort the submit request and prioritize any existing validation requests you can use the `hx-sync="this:abort"` strategy on the form tag.
\`\`\`html
\`\`\`
When implementing active search functionality the hx-trigger attribute's `delay` modifier can be used to debounce the user's input and avoid making multiple requests while the user types. However, once a request is made, if the user begins typing again a new request will begin even if the previous one has not finished processing. This example will cancel any in-flight requests and use only the last request. In cases where the search input is contained within the target, then using `hx-sync` like this also helps reduce the chances that the input will be replaced while the user is still typing.
\`\`\`html
\`\`\`
```
# attributes/hx-target.md
```md
+++
title = "hx-target"
description = """\
The hx-target attribute in htmx allows you to target a different element for swapping than the one issuing the AJAX \
request."""
+++
The `hx-target` attribute allows you to target a different element for swapping than the one issuing the AJAX
request. The value of this attribute can be:
* A CSS query selector of the element to target.
* `this` which indicates that the element that the `hx-target` attribute is on is the target.
* `closest ` which will find the [closest](https://developer.mozilla.org/docs/Web/API/Element/closest)
ancestor element or itself, that matches the given CSS selector
(e.g. `closest tr` will target the closest table row to the element).
* `find ` which will find the first child descendant element that matches the given CSS selector.
* `next` which resolves to [element.nextElementSibling](https://developer.mozilla.org/docs/Web/API/Element/nextElementSibling)
* `next ` which will scan the DOM forward for the first element that matches the given CSS selector.
(e.g. `next .error` will target the closest following sibling element with `error` class)
* `previous` which resolves to [element.previousElementSibling](https://developer.mozilla.org/docs/Web/API/Element/previousElementSibling)
* `previous ` which will scan the DOM backwards for the first element that matches the given CSS selector.
(e.g. `previous .error` will target the closest previous sibling with `error` class)
Here is an example that targets a div:
\`\`\`html
\`\`\`
The response from the `/register` url will be appended to the `div` with the id `response-div`.
This example uses `hx-target="this"` to make a link that updates itself when clicked:
\`\`\`html
New link
\`\`\`
## Notes
* `hx-target` is inherited and can be placed on a parent element
```
# attributes/hx-trigger.md
```md
+++
title = "hx-trigger"
description = """\
The hx-trigger attribute in htmx allows you to specify what triggers an AJAX request. Supported triggers include \
standard DOM events, custom events, polling intervals, and event modifiers. The hx-trigger attribute also allows \
specifying event filtering, timing controls, event bubbling, and multiple trigger definitions for fine-grained \
control over when and how requests are initiated."""
+++
The `hx-trigger` attribute allows you to specify what triggers an AJAX request. A trigger
value can be one of the following:
* An event name (e.g. "click" or "my-custom-event") followed by an event filter and a set of event modifiers
* A polling definition of the form `every `
* A comma-separated list of such events
### Standard Events
Standard events refer to [web API events](https://developer.mozilla.org/en-US/docs/Web/API/Element#events) (e.g. click, keydown, mouseup, load).
A standard event, such as `click` can be specified as the trigger like so:
\`\`\`html
Click Me
\`\`\`
#### Standard Event Filters
Events can be filtered by enclosing a boolean javascript expression in square brackets after the event name. If
this expression evaluates to `true` the event will be triggered, otherwise it will be ignored. Standard event filters [require eval](@/docs.md#configuration-options).
\`\`\`html
Control Click Me
\`\`\`
This event will trigger if a click event is triggered with the `event.ctrlKey` property set to true.
Conditions can also refer to global functions or state
\`\`\`html
Control Click Me
\`\`\`
And can also be combined using the standard javascript syntax
\`\`\`html
Control-Shift Click Me
\`\`\`
Note that all symbols used in the expression will be resolved first against the triggering event, and then next
against the global namespace, so `myEvent[foo]` will first look for a property named `foo` on the event, then look
for a global symbol with the name `foo`
#### Standard Event Modifiers
Standard events can also have modifiers that change how they behave. The modifiers are:
* `once` - the event will only trigger once (e.g. the first click)
* `changed` - the event will only fire if the value of the element has changed. Please pay attention `change` is the name of the event and `changed` is the name of the modifier.
* `delay:` - a delay will occur before an event triggers a request. If the event
is seen again it will reset the delay.
* `throttle:` - a throttle will occur after an event triggers a request. If the event
is seen again before the delay completes, it is ignored, the element will trigger at the end of the delay.
* `from:` - allows the event that triggers a request to come from another element in the document (e.g. listening to a key event on the body, to support hot keys)
* A standard CSS selector resolves to all elements matching that selector. Thus, `from:input` would listen on every input on the page.
* The CSS selector is only evaluated once and is not re-evaluated when the page changes. If you need to detect dynamically added elements use a [standard event filter](#standard-event-filters), for example `hx-trigger="click[event.target.matches('button')] from:body"` which would [catch](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Event_bubbling) click events from every button on the page.
* The extended CSS selector here allows for the following non-standard CSS values:
* `document` - listen for events on the document
* `window` - listen for events on the window
* `closest ` - finds the [closest](https://developer.mozilla.org/docs/Web/API/Element/closest) ancestor element or itself, matching the given css selector
* `find ` - finds the closest child matching the given css selector
* `next` resolves to [element.nextElementSibling](https://developer.mozilla.org/docs/Web/API/Element/nextElementSibling)
* `next ` scans the DOM forward for the first element that matches the given CSS selector.
(e.g. `next .error` will target the closest following sibling element with `error` class)
* `previous` resolves to [element.previousElementSibling](https://developer.mozilla.org/docs/Web/API/Element/previousElementSibling)
* `previous ` scans the DOM backwards for the first element that matches the given CSS selector.
(e.g. `previous .error` will target the closest previous sibling with `error` class)
* `target:` - allows you to filter via a CSS selector on the target of the event. This can be useful when you want to listen for
triggers from elements that might not be in the DOM at the point of initialization, by, for example, listening on the body,
but with a target filter for a child element
* `consume` - if this option is included the event will not trigger any other htmx requests on parents (or on elements
listening on parents)
* `queue:` - determines how events are queued if an event occurs while a request for another event is in flight. Options are:
* `first` - queue the first event
* `last` - queue the last event (default)
* `all` - queue all events (issue a request for each event)
* `none` - do not queue new events
Here is an example of a search box that searches on `input`, but only if the search value has changed
and the user hasn't typed anything new for 1 second:
\`\`\`html
\`\`\`
The response from the `/search` url will be appended to the `div` with the id `search-results`.
### Non-standard Events
There are some additional non-standard events that htmx supports:
* `load` - triggered on load (useful for lazy-loading something)
* `revealed` - triggered when an element is scrolled into the viewport (also useful for lazy-loading). If you are using `overflow` in css like `overflow-y: scroll` you should use `intersect once` instead of `revealed`.
* `intersect` - fires once when an element first intersects the viewport. This supports two additional options:
* `root:` - a CSS selector of the root element for intersection
* `threshold:` - a floating point number between 0.0 and 1.0, indicating what amount of intersection to fire the event on
### Triggering via the `HX-Trigger` header
If you're trying to fire an event from HX-Trigger response header, you will likely want to
use the `from:body` modifier. E.g. if you send a header like this HX-Trigger: my-custom-event
with a response, an element would likely need to look like this:
\`\`\`html