Htmx Api
+++ title = “Javascript API” +++
While it is not a focus of the library, htmx does provide a small API of helper methods, intended mainly for extension development or for working with events.
The hyperscript 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 toclass
- the class to add
or
elt
- the element to add the class toclass
- the class to adddelay
- delay (in milliseconds ) before class is added
Example
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 AJAXelement
- the element to target (defaults to thebody
)
or
verb
- ‘GET’, ‘POST’, etc.path
- the URL path to make the AJAXselector
- a selector for the target
or
verb
- ‘GET’, ‘POST’, etc.path
- the URL path to make the AJAXcontext
- a context object that contains any of the followingsource
- the source element of the request,hx-*
attrs which affect the request will be resolved against that element and its ancestorsevent
- an event that “triggered” the requesthandler
- a callback that will handle the response HTMLtarget
- the target to swap the response intoswap
- how the response will be swapped in relative to the targetvalues
- values to submit with the requestheaders
- headers to submit with the requestselect
- allows you to select the content you want swapped from a response
Example
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 fromselector
- the selector to find
Example
Property - htmx.config
{#config}
A property holding the configuration htmx uses at runtime.
Note that using a meta tag is the preferred mechanism for setting these properties.
Properties
attributesToSettle:["class", "style", "width", "height"]
- array of strings: the attributes to settle during the settling phaserefreshOnHistoryMiss:false
- boolean: if set totrue
htmx will issue a full page refresh on history misses rather than use an AJAX requestdefaultSettleDelay:20
- int: the default delay between completing the content swap and settling attributesdefaultSwapDelay:0
- int: the default delay between receiving a response from the server and doing the swapdefaultSwapStyle:'innerHTML'
- string: the default swap style to use ifhx-swap
is omittedhistoryCacheSize:10
- int: the number of pages to keep inlocalStorage
for history supporthistoryEnabled:true
- boolean: whether or not to use historyincludeIndicatorStyles:true
- boolean: if true, htmx will inject a small amount of CSS into the page to make indicators invisible unless thehtmx-indicator
class is presentindicatorClass:'htmx-indicator'
- string: the class to place on indicators when a request is in flightrequestClass:'htmx-request'
- string: the class to place on triggering elements when a request is in flightaddedClass:'htmx-added'
- string: the class to temporarily place on elements that htmx has added to the DOMsettlingClass:'htmx-settling'
- string: the class to place on target elements when htmx is in the settling phaseswappingClass:'htmx-swapping'
- string: the class to place on target elements when htmx is in the swapping phaseallowEval:true
- boolean: allows the use of eval-like functionality in htmx, to enablehx-vars
, trigger conditions & script tag evaluation. Can be set tofalse
for CSP compatibility.allowScriptTags:true
- boolean: allows script tags to be evaluated in new contentinlineScriptNonce:''
- string: the nonce to add to inline scriptsinlineStyleNonce:''
- string: the nonce to add to inline styleswithCredentials:false
- boolean: allow cross-site Access-Control requests using credentials such as cookies, authorization headers or TLS client certificatestimeout:0
- int: the number of milliseconds a request can take before automatically being terminatedwsReconnectDelay:'full-jitter'
- string/function: the default implementation ofgetWebSocketReconnectDelay
for reconnecting after unexpected connection loss by the event codeAbnormal Closure
,Service Restart
orTry Again Later
wsBinaryType:'blob'
- string: the the type of binary data being received over the WebSocket connectiondisableSelector:"[hx-disable], [data-hx-disable]"
- array of strings: htmx will not process elements with this attribute on it or a parentscrollBehavior:'smooth'
- string: the behavior for a boosted link on page transitions. The allowed values areauto
andsmooth
. Smooth will smoothscroll to the top of the page while auto will behave like a vanilla link.defaultFocusScroll:false
- boolean: if the focused element should be scrolled into view, can be overridden using the focus-scroll swap modifiergetCacheBusterParam:false
- boolean: if set to true htmx will append the target element to theGET
request in the formatorg.htmx.cache-buster=targetElementId
globalViewTransitions:false
- boolean: if set totrue
, htmx will use the View Transition API when swapping in new content.methodsThatUseUrlParams:["get"]
- array of strings: htmx will format requests with these methods by encoding their parameters in the URL, not the request bodyselfRequestsOnly:true
- boolean: whether to only allow AJAX requests to the same domain as the current documentignoreTitle:false
- boolean: if set totrue
htmx will not update the title of the document when atitle
tag is found in new contentscrollIntoViewOnBoost:true
- boolean: whether or not the target of a boosted element is scrolled into the viewport. Ifhx-target
is omitted on a boosted element, the target defaults tobody
, 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 |
Example
Property - htmx.createEventSource
{#createEventSource}
A property used to create new Server Sent Event sources. This can be updated to provide custom SSE setup.
Value
func(url)
- a function that takes a URL string and returns a newEventSource
Example
Property - htmx.createWebSocket
{#createWebSocket}
A property used to create new WebSocket. This can be updated to provide custom WebSocket setup.
Value
func(url)
- a function that takes a URL string and returns a newWebSocket
Example
Method - htmx.defineExtension()
{#defineExtension}
Defines a new htmx extension.
Parameters
name
- the extension nameext
- the extension definition
Example
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, inclusiveselector
- the selector to match
Example
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, inclusiveselector
- the selector to match
Example
Method - htmx.logAll()
{#logAll}
Log all htmx events, useful for debugging.
Example
Method - htmx.logNone()
{#logNone}
Log no htmx events, call this to turn off the debugger if you previously enabled it.
Example
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
Method - htmx.off()
{#off}
Removes an event listener from an element
Parameters
eventName
- the event name to remove the listener fromlistener
- the listener to remove
or
target
- the element to remove the listener fromeventName
- the event name to remove the listener fromlistener
- the listener to remove
Example
Method - htmx.on()
{#on}
Adds an event listener to an element
Parameters
eventName
- the event name to add the listener forlistener
- the listener to add
or
target
- the element to add the listener toeventName
- the event name to add the listener forlistener
- the listener to add
Example
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
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
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
Method - htmx.remove()
{#remove}
Removes an element from the DOM
Parameters
elt
- element to remove
or
elt
- element to removedelay
- delay (in milliseconds ) before element is removed
Example
Method - htmx.removeClass()
{#removeClass}
Removes a class from the given element
Parameters
elt
- element to remove the class fromclass
- the class to remove
or
elt
- element to remove the class fromclass
- the class to removedelay
- delay (in milliseconds ) before class is removed
Example
Method - htmx.removeExtension()
{#removeExtension}
Removes the given extension from htmx
Parameters
name
- the name of the extension to remove
Example
Method - htmx.swap()
{#swap}
Performs swapping (and settling) of HTML content
Parameters
target
- the HTML element or string selector of swap targetcontent
- string representation of content to be swappedswapSpec
- swapping specification, representing parameters fromhx-swap
swapStyle
(required) - swapping style (innerHTML
,outerHTML
,beforebegin
etc)swapDelay
,settleDelay
(number) - delays before swapping and settling respectivelytransition
(bool) - whether to use HTML transitions for swapignoreTitle
(bool) - disables page title updateshead
(string) - specifieshead
tag handling strategy (merge
orappend
). Leave empty to disable head handlingscroll
,scrollTarget
,show
,showTarget
,focusScroll
- specifies scroll handling after swap
swapOptions
- additional optional parameters for swappingselect
- selector for the content to be swapped (equivalent ofhx-select
)selectOOB
- selector for the content to be swapped out-of-band (equivalent ofhx-select-oob
)eventInfo
- an object to be attached tohtmx:afterSwap
andhtmx:afterSettle
elementsanchor
- an anchor element that triggered scroll, will be scrolled into view on settle. Provides simple alternative to full scroll handlingcontextElement
- DOM element that serves as context to swapping operation. Currently used to find extensions enabled for specific elementafterSwapCallback
,afterSettleCallback
- callback functions called after swap and settle respectively. Take no arguments
Example
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 classclass
- the class to take
Example
Method - htmx.toggleClass()
{#toggleClass}
Toggles the given class on an element
Parameters
elt
- the element to toggle the class onclass
- the class to toggle
Example
Method - htmx.trigger()
{#trigger}
Triggers a given event on an element
Parameters
elt
- the element to trigger the event onname
- the name of the event to triggerdetail
- details for the event
Example
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 onrequest type
- the request type (e.g.get
orpost
) non-GET’s will include the enclosing form of the element. Defaults topost