Htmx provides an extensive events system that can be used to modify and enhance behavior. Eventsare listed below.
htmx:abort
This event is different than other events: htmx does nottrigger it, but ratherlistens for it.
If you send anhtmx:abort
event to an element making a request, it will abort the request:
<buttonid="request-button"hx-post="/example">Issue Request</button><buttononclick="htmx.trigger('#request-button','htmx:abort')">Cancel Request</button>
htmx:afterOnLoad
This event is triggered after an AJAXonload
has finished. Note that this does not mean that the contenthas been swapped or settled yet, only that the request has finished.
detail.elt
- the element that dispatched the request or if the body no longer contains the element then the closest parentdetail.xhr
- theXMLHttpRequest
detail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requesthtmx:afterProcessNode
This event is triggered after htmx has initialized a DOM node. It can be useful for extensions to build additional features onto a node.
detail.elt
- the element being initializedhtmx:afterRequest
This event is triggered after an AJAX request has finished either in the case of a successful request (althoughone that may have returned a remote error code such as a404
) or in a network error situation. This eventcan be paired withhtmx:beforeRequest
to wrap behavior around a request cycle.
detail.elt
- the element that dispatched the request or if the body no longer contains the element then the closest parentdetail.xhr
- theXMLHttpRequest
detail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requestdetail.successful
- true if the response has a 20x status code or is markeddetail.isError = false
in thehtmx:beforeSwap
event, else falsedetail.failed
- true if the response does not have a 20x status code or is markeddetail.isError = true
in thehtmx:beforeSwap
event, else falsehtmx:afterSettle
This event is triggered after the DOM hassettled.
detail.elt
- the updated elementdetail.xhr
- theXMLHttpRequest
detail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requesthtmx:afterSwap
This event is triggered after new content has beenswapped into the DOM.
detail.elt
- the swapped in elementdetail.xhr
- theXMLHttpRequest
detail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requesthtmx:beforeCleanupElement
This event is triggered before htmxdisables an element or removes it from the DOM.
detail.elt
- the element to be cleaned uphtmx:beforeOnLoad
This event is triggered before any response processing occurs. If you callpreventDefault()
on the event to cancel it, no swap will occur.
detail.elt
- the element that dispatched the requestdetail.xhr
- theXMLHttpRequest
detail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requesthtmx:beforeProcessNode
This event is triggered before htmx initializes a DOM node and has processed all of itshx-
attributes. This gives extensions and other external code the ability to modify the contents of a DOM node before it is processed.
detail.elt
- the element being initializedhtmx:beforeRequest
This event is triggered before an AJAX request is issued. If you callpreventDefault()
on the event to cancel it, no request will occur.
detail.elt
- the element that dispatched the requestdetail.xhr
- theXMLHttpRequest
detail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requesthtmx:beforeSend
This event is triggered right before a request is sent. You may not cancel the request with this event.
detail.elt
- the element that dispatched the requestdetail.xhr
- theXMLHttpRequest
detail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requesthtmx:beforeSwap
This event is triggered before any new content has beenswapped into the DOM.Most values ondetail
can be set to override subsequent behavior, other than where response headers take precedence.If you callpreventDefault()
on the event to cancel it, no swap will occur.
You can modify the default swap behavior by modifying theshouldSwap
,selectOverride
,swapOverride
andtarget
properties of the event detail.See the documentation onconfiguring swapping for more details.
detail.elt
- the target of the swapdetail.xhr
- theXMLHttpRequest
detail.requestConfig
- the configuration of the AJAX requestdetail.requestConfig.elt
- the element that dispatched the requestdetail.shouldSwap
- if the content will be swapped (defaults tofalse
for non-200 response codes)detail.ignoreTitle
- iftrue
any title tag in the response will be ignoreddetail.isError
- whether error events should be triggered and also determines the values ofdetail.successful
anddetail.failed
in later eventsdetail.serverResponse
- the server response as text to be used for the swapdetail.selectOverride
- add this to use instead of anhx-select
valuedetail.swapOverride
- add this to use instead of anhx-swap
valuedetail.target
- the target of the swaphtmx:beforeTransition
This event is triggered before aView Transitionwrapped swap occurs. If you callpreventDefault()
on the event to cancel it, the View Transition will not occur and the normal swapping logic willhappen instead.
detail.elt
- the element that dispatched the requestdetail.xhr
- theXMLHttpRequest
detail.requestConfig
- the configuration of the AJAX requestdetail.shouldSwap
- if the content will be swapped (defaults tofalse
for non-200 response codes)detail.target
- the target of the swaphtmx:configRequest
This event is triggered after htmx has collected parameters for inclusion in the request. It can beused to include or update the parameters that htmx will send:
document.body.addEventListener('htmx:configRequest',function(evt) {evt.detail.parameters['auth_token'] =getAuthToken();// add a new parameter into the mix});
Note that if an input value appears more than once the value in theparameters
object will be an array, ratherthan a single value.
detail.parameters
- the parameters that will be submitted in the requestdetail.unfilteredParameters
- the parameters that were found before filtering byhx-params
detail.headers
- the request headersdetail.elt
- the element that triggered the requestdetail.target
- the target of the requestdetail.verb
- the HTTP verb in usehtmx:confirm
This event is fired on every trigger for a request (not just on elements that have a hx-confirm attribute).It allows you to cancel (or delay) issuing the AJAX request.If you callpreventDefault()
on the event, it will not issue the given request.Thedetail
object contains a function,evt.detail.issueRequest(skipConfirmation=false)
, that can be used to issue the actual AJAX request at a later point.Combining these two features allows you to create an asynchronous confirmation dialog.
Here is a basic example that shows the basic usage of thehtmx:confirm
event without altering the default behavior:
document.body.addEventListener('htmx:confirm',function(evt) {// 0. To modify the behavior only for elements with the hx-confirm attribute,// check if evt.detail.target.hasAttribute('hx-confirm')// 1. Prevent the default behavior (this will prevent the request from being issued)evt.preventDefault();// 2. Do your own logic hereconsole.log(evt.detail)// 3. Manually issue the request when you are readyevt.detail.issueRequest();// or evt.detail.issueRequest(true) to skip the built-in window.confirm()});
And here is an example usingsweet alert on any element with aconfirm-with-sweet-alert="{question}"
attribute on it:
document.body.addEventListener('htmx:confirm',function(evt) {// 1. The requirement to show the sweet alert is that the element has a confirm-with-sweet-alert// attribute on it, if it doesn't we can return early and let the default behavior happenif(!evt.detail.target.hasAttribute('confirm-with-sweet-alert'))return// 2. Get the question from the attributeconstquestion=evt.detail.target.getAttribute('confirm-with-sweet-alert');// 3. Prevent the default behavior (this will prevent the request from being issued)evt.preventDefault();// 4. Show the sweet alertswal({ title:"Are you sure?", text:question||"Are you sure you want to continue?", icon:"warning", buttons:true, dangerMode:true, }).then((confirmed)=>{if(confirmed) {// 5. If the user confirms, we can manually issue the requestevt.detail.issueRequest(true);// true to skip the built-in window.confirm() } });});
detail.elt
- the element in questiondetail.etc
- additional request information (mostly unused)detail.issueRequest(skipConfirmation=false)
- a function that can be invoked to issue the request (should be paired withevt.preventDefault()
!), if skipConfirmation istrue
the originalwindow.confirm()
is not executeddetail.path
- the path of the requestdetail.target
- the element that triggered the requestdetail.triggeringEvent
- the original event that triggered this requestdetail.verb
- the verb of the request (e.g.GET
)detail.question
- the question passed tohx-confirm
attribute (only available ifhx-confirm
attribute is present)htmx:historyCacheError
This event is triggered when an attempt to save the cache tolocalStorage
fails
detail.cause
- theException
that was thrown when attempting to save history tolocalStorage
htmx:historyCacheMiss
This event is triggered when a cache miss occurs when restoring history
detail.xhr
- theXMLHttpRequest
that will retrieve the remote content for restorationdetail.path
- the path and query of the page being restoredhtmx:historyCacheMissError
This event is triggered when a cache miss occurs and a response has been retrieved from the serverfor the content to restore, but the response is an error (e.g.404
)
detail.xhr
- theXMLHttpRequest
detail.path
- the path and query of the page being restoredhtmx:historyCacheMissLoad
This event is triggered when a cache miss occurs and a response has been retrieved successfully from the serverfor the content to restore
detail.xhr
- theXMLHttpRequest
detail.path
- the path and query of the page being restoredhtmx:historyRestore
This event is triggered when htmx handles a history restoration action
detail.path
- the path and query of the page being restoredhtmx:beforeHistorySave
This event is triggered before the content is saved in the history api.
detail.path
- the path and query of the page being restoreddetail.historyElt
- the history element being restored intohtmx:load
This event is triggered when a new node is loaded into the DOM by htmx.
detail.elt
- the newly added elementhtmx:noSSESourceError
This event is triggered when an element refers to an SSE event in its trigger, but no parent SSE source has been defined
detail.elt
- the element with the bad SSE triggerhtmx:oobAfterSwap
This event is triggered as part of anout of band swap and behaves identically to anafter swap event
detail.elt
- the swapped in elementdetail.shouldSwap
- if the content will be swapped (defaults totrue
)detail.target
- the target of the swapdetail.fragment
- the response fragmenthtmx:oobBeforeSwap
This event is triggered as part of anout of band swap and behaves identically to abefore swap event
detail.elt
- the target of the swapdetail.shouldSwap
- if the content will be swapped (defaults totrue
)detail.target
- the target of the swapdetail.fragment
- the response fragmenthtmx:oobErrorNoTarget
This event is triggered when anout of band swap does not have a corresponding elementin the DOM to switch with.
detail.content
- the element with the bad oobid
htmx:onLoadError
This event is triggered when an error occurs during theload
handling of an AJAX call
detail.xhr
- theXMLHttpRequest
detail.elt
- the element that triggered the requestdetail.target
- the target of the requestdetail.exception
- the exception that occurreddetail.requestConfig
- the configuration of the AJAX requesthtmx:prompt
This event is triggered after a prompt has been shown to the user with thehx-prompt
attribute. If this event is cancelled, the AJAX request will not occur.
detail.elt
- the element that triggered the requestdetail.target
- the target of the requestdetail.prompt
- the user response to the prompthtmx:beforeHistoryUpdate
This event is triggered before a history update is performed. It can beused to modify thepath
ortype
used to update the history.
detail.history
- thepath
andtype
(push, replace) for the history updatedetail.xhr
- theXMLHttpRequest
detail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requesthtmx:pushedIntoHistory
This event is triggered after a URL has been pushed into history.
detail.path
- the path and query of the URL that has been pushed into historyhtmx:replacedInHistory
This event is triggered after a URL has been replaced in history.
detail.path
- the path and query of the URL that has been replaced in historyhtmx:responseError
This event is triggered when an HTTP error response occurs
detail.xhr
- theXMLHttpRequest
detail.elt
- the element that triggered the requestdetail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requesthtmx:sendAbort
This event is triggered when a request is aborted
detail.xhr
- theXMLHttpRequest
detail.elt
- the element that triggered the requestdetail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requesthtmx:sendError
This event is triggered when a network error prevents an HTTP request from occurring
detail.xhr
- theXMLHttpRequest
detail.elt
- the element that triggered the requestdetail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requesthtmx:sseError
This event is triggered when an error occurs with an SSE source
detail.elt
- the element with the bad SSE sourcedetail.error
- the errordetail.source
- the SSE sourcehtmx:swapError
This event is triggered when an error occurs during the swap phase
detail.xhr
- theXMLHttpRequest
detail.elt
- the element that triggered the requestdetail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requesthtmx:targetError
This event is triggered when a bad selector is used for ahx-target
attribute (e.g. anelement ID without a preceding#
)
detail.elt
- the element that triggered the requestdetail.target
- the bad CSS selectorhtmx:timeout
This event is triggered when a request timeout occurs. This wraps the typicaltimeout
event of XMLHttpRequest.
Timeout time can be set usinghtmx.config.timeout
or per element usinghx-request
detail.elt
- the element that dispatched the requestdetail.xhr
- theXMLHttpRequest
detail.target
- the target of the requestdetail.requestConfig
- the configuration of the AJAX requesthtmx:trigger
This event is triggered whenever an AJAX request would be, even if no AJAX request is specified. Itis primarily intended to allowhx-trigger
to execute client-side scripts; AJAX requests have moregranular events available, likehtmx:beforeRequest
orhtmx:afterRequest
.
detail.elt
- the element that triggered the requesthtmx:validateUrl
This event is triggered before a request is made, allowing you to validate the URL that htmx is going to request. IfpreventDefault()
is invoked on the event, the request will not be made.
document.body.addEventListener('htmx:validateUrl',function(evt) {// only allow requests to the current server as well as myserver.comif(!evt.detail.sameHost&&evt.detail.url.hostname !=="myserver.com") {evt.preventDefault(); }});
detail.elt
- the element that triggered the requestdetail.url
- the URL Object representing the URL that a request will be sent to.detail.sameHost
- will betrue
if the request is to the same host as the documenthtmx:validation:validate
This event is triggered before an element is validated. It can be used with theelt.setCustomValidity()
methodto implement custom validation rules.
<formhx-post="/test"> <input_="on htmx:validation:validate if my.value != 'foo' call me.setCustomValidity('Please enter the value foo') else call me.setCustomValidity('')"name="example"></form>
detail.elt
- the element to be validatedhtmx:validation:failed
This event is triggered when an element fails validation.
detail.elt
- the element that failed validationdetail.message
- the validation error messagedetail.validity
- the validity object, which contains properties specifying how validation failedhtmx:validation:halted
This event is triggered when a request is halted due to validation errors.
detail.elt
- the element that triggered the requestdetail.errors
- an array of error objects with the invalid elements and errors associated with themhtmx:xhr:abort
This event is triggered when an ajax request aborts
detail.elt
- the element that triggered the requesthtmx:xhr:loadstart
This event is triggered when an ajax request starts
detail.elt
- the element that triggered the requesthtmx:xhr:loadend
This event is triggered when an ajax request finishes
detail.elt
- the element that triggered the requesthtmx:xhr:progress
This event is triggered periodically when an ajax request that supports progress is in flight
detail.elt
- the element that triggered the request