While it is not a focus of the library, htmx does provide a small API of helper methods, intended mainly forextension development or for working withevents.
Thehyperscript project is intended to provide more extensive scripting supportfor htmx-based applications.
htmx.addClass()
This method adds a class to the given element.
elt
- the element to add the class toclass
- the class to addor
elt
- the element to add the class toclass
- the class to adddelay
- delay (in milliseconds ) before class is added// 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 secondhtmx.addClass(htmx.find('#demo'),'myClass',1000);
htmx.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.
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 targetor
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// issue a GET to /example and put the response HTML into #myDivhtmx.ajax('GET','/example','#myDiv')// issue a GET to /example and replace #myDiv with the responsehtmx.ajax('GET','/example', {target:'#myDiv', swap:'outerHTML'})// execute some code after the content has been inserted into the DOMhtmx.ajax('GET','/example','#myDiv').then(()=>{// this code will be executed after the 'htmx:afterOnLoad' event,// and before the 'htmx:xhr:loadend' eventconsole.log('Content inserted successfully!'); });
htmx.closest()
Finds the closest matching element in the given elements parentage, inclusive of the element
elt
- the element to find the selector fromselector
- the selector to find// find the closest enclosing div of the element with the id 'demo'htmx.closest(htmx.find('#demo'),'div');
htmx.config
A property holding the configuration htmx uses at runtime.
Note that using ameta tag is the preferred mechanism for setting these 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: thenonce to add to inline scriptsinlineStyleNonce:''
- string: thenonce 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: thethe 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 parentdisableInheritance:false
- boolean: If it is set totrue
, the inheritance of attributes is completely disabled and you can explicitly specify the inheritance with thehx-inherit attribute.scrollBehavior:'instant'
- string: the scroll behavior when using theshow modifier withhx-swap
. The allowed values areinstant
(scrolling should happen instantly in a single jump),smooth
(scrolling should animate smoothly) andauto
(scroll behavior is determined by the computed value ofscroll-behavior).defaultFocusScroll:false
- boolean: if the focused element should be scrolled into view, can be overridden using thefocus-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 theView Transition 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 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 aproxy objecthtmx.config.responseHandling:[...]
- HtmxResponseHandlingConfig[]: the defaultResponse Handling behavior for response status codes can be configured here to either swap or errorhtmx.config.allowNestedOobSwaps:true
- boolean: whether to process OOB swaps on elements that are nested within the main response element. SeeNested OOB Swaps.// update the history cache size to 30htmx.config.historyCacheSize=30;
htmx.createEventSource
A property used to create newServer Sent Event sources. This can be updatedto provide custom SSE setup.
func(url)
- a function that takes a URL string and returns a newEventSource
// override SSE event sources to not use credentialshtmx.createEventSource=function(url) {returnnew EventSource(url, {withCredentials:false}); };
htmx.createWebSocket
A property used to create newWebSocket. This can be updatedto provide custom WebSocket setup.
func(url)
- a function that takes a URL string and returns a newWebSocket
// override WebSocket to use a specific protocolhtmx.createWebSocket=function(url) {returnnew WebSocket(url, ['wss']); };
htmx.defineExtension()
Defines a new htmxextension.
name
- the extension nameext
- the extension definition// defines a silly extension that just logs the name of all events triggeredhtmx.defineExtension("silly", {onEvent:function(name,evt) {console.log("Event "+name+" was triggered!") } });
htmx.find()
Finds an element matching the selector
selector
- the selector to matchor
elt
- the root element to find the matching element in, inclusiveselector
- the selector to match// find div with id my-divvardiv=htmx.find("#my-div")// find div with id another-div within that divvaranotherDiv=htmx.find(div,"#another-div")
htmx.findAll()
Finds all elements matching the selector
selector
- the selector to matchor
elt
- the root element to find the matching elements in, inclusiveselector
- the selector to match// find all divsvarallDivs=htmx.findAll("div")// find all paragraphs within a given divvarallParagraphsInMyDiv=htmx.findAll(htmx.find("#my-div"),"p")
htmx.logAll()
Log all htmx events, useful for debugging.
htmx.logAll();
htmx.logNone()
Log no htmx events, call this to turn off the debugger if you previously enabled it.
htmx.logNone();
htmx.logger
The logger htmx uses to log with
func(elt, eventName, detail)
- a function that takes an element, eventName and event detail and logs ithtmx.logger=function(elt,event,data) {if(console) {console.log("INFO:", event,elt,data); } }
htmx.off()
Removes an event listener from an element
eventName
- the event name to remove the listener fromlistener
- the listener to removeor
target
- the element to remove the listener fromeventName
- the event name to remove the listener fromlistener
- the listener to remove// remove this click listener from the bodyhtmx.off("click",myEventListener);// remove this click listener from the given divhtmx.off("#my-div","click",myEventListener)
htmx.on()
Adds an event listener to an element
eventName
- the event name to add the listener forlistener
- the listener to addoptions
- anoptions object (or auseCapture boolean) to add to the event listener (optional)or
target
- the element to add the listener toeventName
- the event name to add the listener forlistener
- the listener to addoptions
- anoptions object (or auseCapture boolean) to add to the event listener (optional)// add a click listener to the bodyvarmyEventListener=htmx.on("click",function(evt){console.log(evt); });// add a click listener to the given divvarmyEventListener=htmx.on("#my-div","click",function(evt){console.log(evt); });// add a click listener to the given div that should only be invoked oncevarmyEventListener=htmx.on("#my-div","click",function(evt){console.log(evt); }, { once:true});
htmx.onLoad()
Adds a callback for thehtmx:load
event. This can be used to process new content, for exampleinitializing the content with a javascript library
callback(elt)
- the callback to call on newly loaded contenthtmx.onLoad(function(elt){MyLibrary.init(elt); })
htmx.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 eithers
orms
. All other values useparseFloat
str
- timing string// returns 3000varmilliseconds=htmx.parseInterval("3s");// returns 3 - Cautionvarmilliseconds=htmx.parseInterval("3m");
htmx.process()
Processes new content, enabling htmx behavior. This can be useful if you have content that is added to the DOMoutside of the normal htmx request cycle but still want htmx attributes to work.
elt
- element to process document.body.innerHTML="<div hx-get='/example'>Get it!</div>"// process the newly added contenthtmx.process(document.body);
htmx.remove()
Removes an element from the DOM
elt
- element to removeor
elt
- element to removedelay
- delay (in milliseconds ) before element is removed// removes my-div from the DOMhtmx.remove(htmx.find("#my-div"));// removes my-div from the DOM after a delay of 2 secondshtmx.remove(htmx.find("#my-div"),2000);
htmx.removeClass()
Removes a class from the given element
elt
- element to remove the class fromclass
- the class to removeor
elt
- element to remove the class fromclass
- the class to removedelay
- delay (in milliseconds ) before class is removed// removes .myClass from my-divhtmx.removeClass(htmx.find("#my-div"),"myClass");// removes .myClass from my-div after 6 secondshtmx.removeClass(htmx.find("#my-div"),"myClass",6000);
htmx.removeExtension()
Removes the given extension from htmx
name
- the name of the extension to removehtmx.removeExtension("my-extension");
htmx.swap()
Performs swapping (and settling) of HTML content
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 swapswapOptions
- additionaloptional 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// swap #output element inner HTML with div element with "Swapped!" texthtmx.swap("#output","<div>Swapped!</div>", {swapStyle:'innerHTML'});
htmx.takeClass()
Takes the given class from its siblings, so that among its siblings, only the given element will have the class.
elt
- the element that will take the classclass
- the class to take// takes the selected class from tab2's siblingshtmx.takeClass(htmx.find("#tab2"),"selected");
htmx.toggleClass()
Toggles the given class on an element
elt
- the element to toggle the class onclass
- the class to toggle// toggles the selected class on tab2htmx.toggleClass(htmx.find("#tab2"),"selected");
htmx.trigger()
Triggers a given event on an element
elt
- the element to trigger the event onname
- the name of the event to triggerdetail
- details for the event// triggers the myEvent event on #tab2 with the answer 42htmx.trigger("#tab2","myEvent", {answer:42});
htmx.values()
Returns the input values that would resolve for a given element via the htmx value resolution mechanism
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
// gets the values associated with this formvarvalues=htmx.values(htmx.find("#myForm"));