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 requestevent
- 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 request // 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 phasedefaultSettleDelay: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 compatibilityuseTemplateFragments:false
- boolean: use HTML template tags for parsing content from the server. This allows you to use Out of Band content when returning things like table rows, but it is not IE11 compatible.withCredentials:false
- boolean: allow cross-site Access-Control requests using credentials such as cookies, authorization headers or TLS client certificateswsReconnectDelay: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
scrollBehavior:smooth
- string: the behavior for a boosted link on page transitions. The allowed values are auto
and smooth
. Smooth will smoothscroll to the top of the page while auto will behave like a vanilla link. // 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 addor
target
- the element to add the listener toeventName
- the event name to add the listener forlistener
- the listener to add // 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); });
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.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"));