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"));