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()

This method adds a class to the given element.

#Parameters

or

#Example
  // 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);

#Method - 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.

#Parameters

or

or

#Example
    // 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!');
    });

#Method - htmx.closest()

Finds the closest matching element in the given elements parentage, inclusive of the element

#Parameters
#Example
  // find the closest enclosing div of the element with the id 'demo'
  htmx.closest(htmx.find('#demo'), 'div');

#Property - 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.

#Properties
#Example
  // update the history cache size to 30
  htmx.config.historyCacheSize = 30;

#Property - htmx.createEventSource

A property used to create new Server Sent Event sources. This can be updated to provide custom SSE setup.

#Value
#Example
  // override SSE event sources to not use credentials
  htmx.createEventSource = function(url) {
    return new EventSource(url, {withCredentials:false});
  };

#Property - htmx.createWebSocket

A property used to create new WebSocket. This can be updated to provide custom WebSocket setup.

#Value
#Example
  // override WebSocket to use a specific protocol
  htmx.createWebSocket = function(url) {
    return new WebSocket(url, ['wss']);
  };

#Method - htmx.defineExtension()

Defines a new htmx extension.

#Parameters
#Example
  // 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!")
    }
  });

#Method - htmx.find()

Finds an element matching the selector

#Parameters

or

#Example
    // 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")

#Method - htmx.findAll()

Finds all elements matching the selector

#Parameters

or

#Example
    // find all divs
    var allDivs = htmx.findAll("div")

    // find all paragraphs within a given div
    var allParagraphsInMyDiv = htmx.findAll(htmx.find("#my-div"), "p")

#Method - htmx.logAll()

Log all htmx events, useful for debugging.

#Example
    htmx.logAll();

#Method - htmx.logNone()

Log no htmx events, call this to turn off the debugger if you previously enabled it.

#Example
    htmx.logNone();

#Property - htmx.logger

The logger htmx uses to log with

#Value
#Example
    htmx.logger = function(elt, event, data) {
        if(console) {
            console.log("INFO:", event, elt, data);
        }
    }

#Method - htmx.off()

Removes an event listener from an element

#Parameters

or

#Example
    // 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)

#Method - htmx.on()

Adds an event listener to an element

#Parameters

or

#Example
    // 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); });

#Method - 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

#Parameters
#Example
    htmx.onLoad(function(elt){
        MyLibrary.init(elt);
    })

#Method - 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

#Parameters
#Example
    // returns 3000
    var milliseconds = htmx.parseInterval("3s");

    // returns 3 - Caution
    var milliseconds = htmx.parseInterval("3m");

#Method - 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.

#Parameters
#Example
  document.body.innerHTML = "<div hx-get='/example'>Get it!</div>"
  // process the newly added content
  htmx.process(document.body);

#Method - htmx.remove()

Removes an element from the DOM

#Parameters

or

#Example
  // 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);

#Method - htmx.removeClass()

Removes a class from the given element

#Parameters

or

#Example
  // 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);

#Method - htmx.removeExtension()

Removes the given extension from htmx

#Parameters
#Example
  htmx.removeExtension("my-extension");

#Method - htmx.takeClass()

Takes the given class from its siblings, so that among its siblings, only the given element will have the class.

#Parameters
#Example
  // takes the selected class from tab2's siblings
  htmx.takeClass(htmx.find("#tab2"), "selected");

#Method - htmx.toggleClass()

Toggles the given class on an element

#Parameters
#Example
  // toggles the selected class on tab2
  htmx.toggleClass(htmx.find("#tab2"), "selected");

#Method - htmx.trigger()

Triggers a given event on an element

#Parameters
#Example
  // triggers the myEvent event on #tab2 with the answer 42
  htmx.trigger("#tab2", "myEvent", {answer:42});

#Method - htmx.values()

Returns the input values that would resolve for a given element via the htmx value resolution mechanism

#Parameters
#Example
  // gets the values associated with this form
  var values = htmx.values(htmx.find("#myForm"));