What Is HTMX?

Posted in category Htmx on
1582 Words ~8 Minute Reading Time • Subscribe to receive updates on Htmx
Eric David Smith
Software Engineer / Musician / Entrepreneur
What Is HTMX? by Eric David Smith

What Is HTMX?

HTMX is a revolutionary library that allows you to harness modern HTML and make dynamic, responsive web pages without writing JavaScript. It extends HTML and provides capabilities usually reserved for JavaScript, making web development more accessible and maintainable. Whether you are a seasoned developer or just starting, HTMX offers an efficient way to create interactive web experiences.

Installing

Installing HTMX is a straightforward process. You can include it in your project by adding the following script tag to the head of your HTML:

<script src="https://unpkg.com/htmx.org@1.6.1"></script>

Or, if you prefer, you can install it via npm:

npm install htmx.org

Then include it in your JavaScript file:

import htmx from "htmx.org";

AJAX

AJAX (Asynchronous JavaScript and XML) allows web pages to update asynchronously, fetching data from the server without reloading the whole page. HTMX provides AJAX capabilities through simple HTML attributes, making it incredibly easy to fetch, send, and display data.

For example, to fetch content from a specific URL when a user clicks on a div:

<div hx-get="/path/to/resource">Click me!</div>

HTMX takes care of the rest, making the GET request to the specified URL and replacing the content of the div with the response.

Triggers

Triggers are the events that initiate an HTMX action. They can be user actions like a click, a hover, or even a form submission. By defining triggers, you control when and how HTMX performs actions.

For example, to make a request when a button is clicked:

<button hx-post="/path/to/action">Click me!</button>

Here, hx-post tells HTMX to make a POST request to the given URL when the button is clicked.

Trigger Modifiers

Modifiers allow you to change the behavior of triggers. For instance, you can use a delay, prevent default behavior, or limit the number of times a trigger fires.

<button hx-post="/path/to/action" hx-trigger="click delay:1s">Click me</button>

This example introduces a one-second delay after the click before the action is triggered.

Trigger Filters

Filters enable you to specify conditions under which a trigger will fire. This allows for more precise control over user interactions.

<button hx-post="/path/to/action" hx-trigger="click once">Click me</button>

The "once" filter ensures that this action will only be triggered once.

Special Events

HTMX defines several special events that can be used to respond to different stages of a request. This enables fine-grained control over what happens before, during, and after an HTMX call.

Examples include:

<div
  hx-get="/path/to/resource"
  hx-trigger="click"
  hx-beforeRequest="alert('Request is about to be made!')"
  hx-afterOnLoad="alert('Content loaded!')"
>
  Click me
</div>

Polling

Polling is the process of repeatedly making requests to a server at regular intervals. HTMX's hx-poll attribute allows you to easily set up polling.

<div hx-get="/path/to/resource" hx-poll="5s">
  This will update every 5 seconds
</div>

Load Polling

Load polling is a specific type of polling that only starts the next poll after the previous one has completed, ensuring that the requests don't overlap.

<div hx-get="/path/to/resource" hx-poll="load:5s">
  This will update 5 seconds after the previous load completes
</div>

Indicators

Indicators in HTMX provide visual feedback during various stages of a request, such as while a request is in progress or if it fails.

<div hx-get="/path/to/resource" hx-indicator="#loadingIndicator">Click me</div>
<div id="loadingIndicator" style="display:none">Loading...</div>

The loading indicator will be displayed during the request and hidden once it's completed.

Targets

HTMX allows you to specify targets that define where the returned content will be placed. You can set the target using the hx-target attribute.

<div hx-get="/path/to/resource" hx-target="#myTarget">Click me</div>
<div id="myTarget">This content will be replaced</div>

Swapping

Swapping refers to the way HTMX updates the content of a target. You can control the swapping behavior with the hx-swap attribute.

<div hx-get="/path/to/resource" hx-swap="outerHTML fade:0.5s">Click me</div>

The fade option here introduces a fading transition during the content swap.

Synchronization

HTMX offers synchronization features that ensure consistency across simultaneous requests. You can use the hx-swap-oob attribute to enable out-of-band updates.

<div hx-get="/path/to/resource" hx-swap-oob="true">Click me</div>

CSS Transitions

CSS Transitions in HTMX allow you to animate changes to your HTML elements smoothly. You can easily apply CSS transitions using the hx-swap attribute:

<div hx-get="/path/to/resource" hx-swap="outerHTML fade:1s">
  Click me for a smooth transition!
</div>

Out of Band Swaps

Out-of-band (OOB) swaps allow you to update parts of the page that weren't originally targeted in the request:

<div hx-get="/path/to/resource" hx-swap-oob="true">Click me</div>

With OOB swaps, you can specify areas of the page to be updated, even if they were not the original target.

Parameters

You can pass parameters with your HTMX requests using the hx-params attribute:

<div hx-get="/path/to/resource" hx-params="foo='bar'">Click me</div>

Confirming

You can prompt the user for confirmation before a request is made:

<button hx-post="/path/to/delete" hx-confirm="Are you sure?">Delete</button>

Inheritance

HTMX supports inheritance, allowing parent elements to pass attributes to their children:

<div hx-target="#target">
  <button hx-get="/path/to/resource">Click me</button>
</div>

Here, the button inherits the hx-target attribute from its parent div.

Boosting

Boosting is a way to enhance regular HTML forms and links with AJAX, with no need for extra attributes:

<form hx-boost action="/path/to/resource" method="post">...</form>

WebSockets & SSE

HTMX allows integration with WebSockets and Server-Sent Events (SSE), enabling real-time updates:

<div hx-ws-src="/websocket">Real-time content here</div>

History

You can control browser history and navigation with HTMX:

<a href="/new/page" hx-push-url="true">Click me</a>

Requests & Responses

HTMX provides granular control over HTTP requests and how responses are handled:

<div hx-get="/path/to/resource" hx-headers="{'Authorization': 'Bearer TOKEN'}">
  Click me
</div>

Validation

HTMX can work with native HTML validation or custom validation logic:

<form hx-post="/path/to/resource" hx-validate>
  <input type="text" required />
</form>

Animations

Create complex animations using the hx-swap attribute with custom animation specifications.

Extensions

HTMX supports extensions, allowing you to write custom JavaScript to extend functionality.

Events & Logging

HTMX fires various events during its lifecycle, which can be logged or acted upon:

<div
  hx-get="/path/to/resource"
  hx-trigger="click"
  hx-onload="console.log('Loaded!')"
>
  Click me
</div>

Debugging

You can enable debugging in HTMX to get detailed information about what it's doing:

<script>
  htmx.config.logging = true;
</script>

Scripting

HTMX allows custom scripting through its JavaScript API, providing a way to manually trigger actions or bind to events.

Hyperscript

Hyperscript is a companion language to HTMX that allows you to write logic directly in your HTML attributes.

3rd Party Integration

Integrate HTMX with other libraries and frameworks to create cohesive applications.

Caching

HTMX provides caching mechanisms to store responses, minimizing unnecessary requests:

<div hx-get="/path/to/resource" hx-cache="true">Click me</div>

Security

Ensure safe and secure practices with HTMX, considering aspects like Cross-Site Request Forgery (CSRF) protection.

Configuring

Configuration options allow you to globally set preferences and behaviors for HTMX:

<script>
  htmx.config.timeout = 10000;
</script>

Compatibility

HTMX is compatible with all modern browsers, including Chrome, Firefox, Safari, and Edge. It also works with Internet Explorer 11.

Hello World with HTMX Example

Let's create a simple Hello World example using HTMX. We'll create a simple HTML page with a button that, when clicked, will make a request to a server and display the response.

First, create a new directory and add an index.html file:

mkdir htmx-hello-world
cd htmx-hello-world
touch index.html

Next, open the index.html file in your favorite text editor and add the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Hello World</title>
    <script src="https://unpkg.com/htmx.org@1.6.1"></script>
  </head>
  <body>
    <button hx-get="/hello" hx-trigger="click">Click Me!</button>
    <script>
      document.body.addEventListener("htmx:afterRequest", function () {
        alert("Hello, World!");
      });
    </script>
  </body>
</html>

Here, we've added a button with an hx-get attribute that will make a GET request to the /hello endpoint when clicked. We've also added a script that will display an alert when the request is complete.

Now, let's create a simple server using python to handle the request. Let's use the Flask framework to create a simple server. First, install Flask:

pip install flask

Next, create a new file called main.py and add the following code:

from flask import Flask, render_template_string

app = Flask(__name__)

@app.route("/")
def index():
    with open("index.html") as f:
        return f.read()

@app.route("/hello")
def hello():
    return "Hello, World!"

if __name__ == "__main__":
    app.run(port=8080)

Here, we've created a simple Flask server that will serve our index.html file when the / endpoint is requested. We've also created a /hello endpoint that will return the string Hello, World! when requested.

Now, let's run our server:

python main.py

or

python3 main.py

Now, open your browser and navigate to http://localhost:8080. You should see a button that says Click Me!. Click the button and you should see an alert that says Hello, World!.

Congratulations! You've created your first HTMX application!

That's It. HTMX is a Gift 🎁 to the Web!

In this tutorial, you learned about HTMX, a JavaScript library that allows you to create dynamic web applications using HTML attributes. You learned about the various features of HTMX, including polling, indicators, targets, swapping, synchronization, CSS transitions, out-of-band swaps, parameters, confirming, inheritance, boosting, WebSockets and SSE, history, requests and responses, validation, animations, extensions, events and logging, debugging, scripting, hyperscript, 3rd party integration, caching, security, and configuration.

Supporting My Work

Please consider Buying Me A Coffee. I work hard to bring you my best content and any support would be greatly appreciated. Thank you for your support!

Contact


Eric David Smith
Software Engineer / Musician / Entrepreneur

Blog Post Tags