HTMX - Configuring



HTMX is a JavaScript library that extends your HTML with AJAX, CSS Transitions, WebSockets, and Server-Sent Events. This guide will show you how to configure HTMX for your project, covering both basic and advanced setup options to ensure HTMX works smoothly for you.

Getting Started With HTMX

HTMX allows you to add interactive features to your web applications with minimal effort. Start by integrating HTMX into your project and use its attributes to make your HTML elements responsive and dynamic.

Include HTMX in Your Project

To start using HTMX, you need to include it in your HTML file. For this you can check HTMX - Installation.

Verify HTMX Activation

HTMX starts working automatically when the page loads. You don't need to do anything to set it up.

Global Configuration

HTMX provides allows you to set global configuration options that apply to all HTMX elements on your page. You can set global configurations using the htmx.config object.

// Enable template fragments
htmx.config.useTemplateFragments = true;

// Set default swap style
htmx.config.defaultSwapStyle = "outerHTML";

// Set default swap delay (in milliseconds)
htmx.config.defaultSwapDelay = 100;

Here are some commonly used global configuration options:

  • useTemplateFragments: If set to true, HTMX will use template tags for parsing content
  • defaultSwapStyle: Sets the default swap style for all elements (e.g., "innerHTML", "outerHTML")
  • defaultSwapDelay: Sets a default delay (in milliseconds) before swapping content.
  • timeout: Sets the default timeout for AJAX requests (in milliseconds).
  • historyCacheSize Sets the number of history entries to cache.

Overriding Configuration Per-Element

While global configurations apply to all HTMX elements, you can also configure individual elements using attributes.

Here are some commonly used element-specific attributes

  • hx-trigger:Specifies the event that triggers the request.
  • hx-target: Specifies the target element to swap content into
  • hx-swap: Defines how the response content should be swapped in
  • hx-boost: Converts normal anchors and forms into AJAX requests

Example

<button hx-post="/submit" hx-trigger="click" hx-target="#result" hx-swap="outerHTML">
    Submit
</button>

This button will use "outerHTML" swapping regardless of the global defaultSwapStyle setting.

Advanced Configuration Options

HTMX also allows for more advanced configurations using JavaScript. These settings enable you to adjust HTMX to your specific needs.

Example

htmx.config.historyCacheSize = 20;
htmx.config.defaultSettleDelay = 100;
htmx.config.globalViewTransitions = true;
htmx.config.getCacheBusterParam = true;

This configuration:

  • Increases the history cache size
  • Sets a default settle delay for smoother transition
  • Enables view transitions API globally
  • Adds a cache-busting parameter to GET requests

Custom Headers Configuration

You can add custom headers to all HTMX requests.

htmx.config.headers = {
    'My-Custom-Header': 'my-custom-value'
};

Debugging Configurations

To help with debugging, you can log the current configuration.

console.log(JSON.stringify(htmx.config, null, 2));

This will output the entire configuration object in a readable format.

Dynamic Configurations Changes

You can change configuration dynamically based on user actions or application state.

document.getElementById('toggleHistory').addEventListener('click', function() {
  htmx.config.historyEnabled = !htmx.config.historyEnabled;
  console.log("History is now " + (htmx.config.historyEnabled ? "enabled" : "disabled"));
});

Response Handling Configuration

HTMX allows you to control how server responses are handled on your webpage. You can specify where the response content goes and how it's inserted.

Example

<button hx-get="/api/data"
    hx-target="#result"
    hx-swap="innerHTML"
    hx-select="#data">
Load Data
</button>

This button, when clicked, fetches data from "/api/data", selects the "#data" portion of the response, and inserts it into the "#result" element by replacing its inner HTML.

The "hx-swap" attribute has other options like "outerHTML", "beforebegin", and "afterend" for different insertion methods.

Configuring HTMX

You can configure HTMX in a few different ways, either by using JavaScript or by adding attributes directly to your HTML. Here's an overview of the different configuration options available for setting up HTMX to fit your project

Config Variable Info
htmx.config.historyEnabled Defaults to true, mainly for testing.
htmx.config.historyCacheSize Defaults to 10.
htmx.config.refreshOnHistoryMiss Defaults to false. If true, HTMX will refresh the page instead of using AJAX if history is missing.
htmx.config.defaultSwapStyle Defaults to innerHTML.
htmx.config.defaultSwapDelay Defaults to 0 milliseconds.
htmx.config.defaultSettleDelay Defaults to 20 milliseconds.
htmx.config.includeIndicatorStyles Defaults to true, controls if indicator styles are loaded.
htmx.config.indicatorClass Defaults to htmx-indicator.
htmx.config.requestClass Defaults to htmx-request.
htmx.config.addedClass Defaults to htmx-added.
htmx.config.settlingClass Defaults to htmx-settling.
htmx.config.swappingClass Defaults to htmx-swapping.
htmx.config.allowEval Defaults to true, can disable use of eval for certain features.
htmx.config.allowScriptTags Defaults to true, determine if HTMX processes script tags in new content.
htmx.config.inlineScriptNonce Defaults to empty, meaning no nonce is added to inline scripts.
htmx.config.attributesToSettle Defaults to ["class", "style", "width", "height"], the attributes to settle during the settling phase.
htmx.config.inlineStyleNonce Defaults to empty, meaning no nonce is added to inline styles.
htmx.config.useTemplateFragments Defaults to false, uses HTML template tags for content parsing (not compatible with IE11).
htmx.config.wsReconnectDelay Defaults to full-jitter.
htmx.config.wsBinaryType Defaults to blob, the type of binary data received over WebSocket.
htmx.config.disableSelector Defaults to [hx-disable], [data-hx-disable], HTMX ignores elements with this attribute.
htmx.config.withCredentials Defaults to false, controls cross-site requests with credentials.
htmx.config.timeout Defaults to 0 milliseconds, time before a request is automatically canceled.
htmx.config.scrollBehavior Defaults to smooth, scrolls to the top or behaves like a normal link.
htmx.config.defaultFocusScroll Defaults to false, determines if the focused element should be scrolled into view.
htmx.config.getCacheBusterParam Defaults to false, if true, appends a cache-busting parameter to GET requests.
htmx.config.globalViewTransitions Defaults to false, if true, uses the View Transition API for new content.
htmx.config.methodsThatUseUrlParams Defaults to ["get", "delete"], methods that use URL parameters instead of the request body.
htmx.config.selfRequestsOnly Defaults to true, only allows AJAX requests to the same domain.
htmx.config.ignoreTitle Defaults to false, if true, HTMX will not update the document title.
htmx.config.disableInheritance Disables attribute inheritance, which can be overridden by the hx-inherit attribute.
htmx.config.scrollIntoViewOnBoost Defaults to true, scrolls the target of a boosted element into view.
htmx.config.triggerSpecsCache Defaults to null, cache for evaluated trigger specifications to improve performance.
htmx.config.responseHandling Configures how HTMX handles different response status codes.
htmx.config.allowNestedOobSwaps Defaults to true, allows processing of OOB swaps within nested elements.
Advertisements