Back to overview

Getting started with HTMX

▼ Post information

Author Jef Meijvis Publish date 21/08/2023
Title Getting started with HTMX Id 18
Source 018-getting-started-with-htmx.md Render timestamp Dec 06, 2023, 06:08:31 AM (GMT+1)
Views 40 Tags Frontend
Author Jef Meijvis
Publish date 21/08/2023
Title Getting started with HTMX
Id 18
Source 018-getting-started-with-htmx.md
Render timestamp Dec 06, 2023, 06:08:31 AM (GMT+1)
Views 40
Tags Frontend
opengraph

▼ Table of contents

Share this post:

Getting started with HTMX

All aboard the hypetrain because a new frontend framework just dropped!

HTMX Logo

Image: HTMX Logo

HTMX?

HTMX is a small (14kb) javascript library, that runs client-side in the browser. It's main promise is to expand the current existing html tags by adding attributes to them. In this way, it expands on the existing HTML capabilities and grants access to AJAX, CSS Transitions, WebSockets and Server Sent Events from your HTML.

Frontend

Consider the following index.html file, which is served to the client. It contains a script tag which downloads the HTMX library from UNPKG.

Next up is a button tag, which includes 2 attributes that are specific to HTMX:

  • hx-post='clicked' specifies an endpoint that will receive a post request when clicked.
  • hx-swap='outerHTML' specifies which part of the HTML needs to be replaced by the response from the endpoint. In this case the outerHTML from the button gets replaced.

Code snippet

1
    <script src="https://unpkg.com/htmx.org@1.9.5"></script>
2

3
    <!-- have a button POST a click via AJAX -->
4
    <button hx-post="/clicked" hx-swap="outerHTML">
5
        Click Me
6
    </button>

Frontend

At the backend we need an api that returns html. Multiple backend technologies are possible, but for the sake of demonstration I've set up a Node Express REST API. The API has a single endpoint that accepts a POST request, and returns the button HTML again, but with an updated counter.

Code snippet

1
    import express from 'express';
2
    let port = 3021
3
    let counter = 0;
4

5
    const app = express();
6
    app.post('/', (req, res) => {
7
    counter++;
8
    return res.send('<button hx-post="/clicked" hx-swap="outerHTML">Click Me ' + counter + '</button>');
9
    });
10

11
    app.listen(port, () =>console.log(`Example app listening on port ${port}!`));

Each time the user presses the button, a counter is updated and the new button tag is returned. This is a minimal example, as many more attributes are available. The HTMX example page showcases a lot of UI and UX patterns ands their implementation with UI/UX.

Conclusion

HTMX is a new library that goes back to the old approach of rendering HTML on the server. While I've never tried to create an entire web application using HTMX, it sure does offer an interesting perspective on front-end technologies!

Back to top