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.
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 second
htmx.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 the body
)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 following
source
- 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 #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!');
});
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 a meta 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 to true
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 if hx-swap
is omittedhistoryCacheSize:10
- int: the number of pages to keep in localStorage
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 the htmx-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 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 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 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 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 to true
, the inheritance of attributes is completely disabled and you can explicitly specify the inheritance with the hx-inherit attribute.scrollBehavior:'instant'
- string: the scroll behavior when using the 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).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 the GET
request in the format org.htmx.cache-buster=targetElementId
globalViewTransitions:false
- boolean: if set to true
, htmx will use the View 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 to true
htmx will not update the title of the document when a title
tag is found in new contentscrollIntoViewOnBoost: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 objecthtmx.config.responseHandling:[...]
- HtmxResponseHandlingConfig[]: the default Response 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. See Nested OOB Swaps. // update the history cache size to 30
htmx.config.historyCacheSize = 30;
htmx.createEventSource
A property used to create new Server Sent Event sources. This can be updated to provide custom SSE setup.
func(url)
- a function that takes a URL string and returns a new EventSource
// override SSE event sources to not use credentials
htmx.createEventSource = function(url) {
return new EventSource(url, {withCredentials:false});
};
htmx.createWebSocket
A property used to create new WebSocket. This can be updated to provide custom WebSocket setup.
func(url)
- a function that takes a URL string and returns a new WebSocket
// override WebSocket to use a specific protocol
htmx.createWebSocket = function(url) {
return new WebSocket(url, ['wss']);
};
htmx.defineExtension()
Defines a new htmx extension.
name
- the extension nameext
- the extension definition // 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!")
}
});
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-div
var div = htmx.find("#my-div")
// find div with id another-div within that div
var anotherDiv = 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 divs
var allDivs = htmx.findAll("div")
// find all paragraphs within a given div
var allParagraphsInMyDiv = 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 it htmx.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 body
htmx.off("click", myEventListener);
// remove this click listener from the given div
htmx.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
- an options object (or a useCapture 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
- an options object (or a useCapture boolean) to add to the event listener (optional) // 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 });
htmx.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
callback(elt)
- the callback to call on newly loaded content htmx.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 either s
or ms
. All other values use parseFloat
str
- timing string // returns 3000
var milliseconds = htmx.parseInterval("3s");
// returns 3 - Caution
var milliseconds = htmx.parseInterval("3m");
htmx.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.
elt
- element to process document.body.innerHTML = "<div hx-get='/example'>Get it!</div>"
// process the newly added content
htmx.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 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);
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-div
htmx.removeClass(htmx.find("#my-div"), "myClass");
// removes .myClass from my-div after 6 seconds
htmx.removeClass(htmx.find("#my-div"), "myClass", 6000);
htmx.removeExtension()
Removes the given extension from htmx
name
- the name of the extension to remove htmx.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 from hx-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) - specifies head
tag handling strategy (merge
or append
). Leave empty to disable head handlingscroll
, scrollTarget
, show
, showTarget
, focusScroll
- specifies scroll handling after swapswapOptions
- 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
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!" text
htmx.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 siblings
htmx.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 tab2
htmx.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 42
htmx.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
or post
) non-GET’s will include the enclosing form of the element.
Defaults to post
// gets the values associated with this form
var values = htmx.values(htmx.find("#myForm"));