Skip to main content

Introduction to HTMX

HTMX lets any HTML element talk to the server. You don’t write any JavaScript. Instead, you add a few hx- attributes to your HTML.

Here’s how it works:

  1. You tell HTMX which event to listen for.
  2. When that event happens, HTMX sends a request to the server.
  3. You decide what to do with the response.

1. Choose an event

Use hx-trigger to say which event HTMX should act on. For example, click, change or submit:

<input type="checkbox" hx-trigger="click" ...>

If you leave out hx-trigger, HTMX uses a sensible default. For example, buttons trigger on click and forms trigger on submit.

2. Send a request

Use hx-get, hx-post (or hx-put, hx-patch, hx-delete) to say where the request goes:

<input type="checkbox" hx-trigger="click" hx-post="/todo/1/toggle/">

Now, when you click the checkbox, HTMX sends a POST request to /todo/1/toggle/.

3. Decide what to do with the response

Ignore it

Sometimes you don’t need the response at all. You just want the server to do something, like save to the database. Use hx-swap="none" to leave the page alone:

<button hx-post="/ping/" hx-swap="none">Ping</button>

If the server sends back an empty response, there’s nothing to put on the page anyway.

Put it on the page

Usually the server sends back a small piece of HTML, called a partial. HTMX puts that partial into the page for you.

By default, HTMX puts the response inside the element that made the request. You can change this with hx-swap:

hx-swap value What it does
innerHTML (default) Replace the contents of the target
outerHTML Replace the whole target element
beforeend Append inside the target, after its last child
afterbegin Prepend inside the target, before its first child
beforebegin Insert just before the target
afterend Insert just after the target
delete Delete the target, whatever the response
none Do nothing with the response

Choose where it goes

Use hx-target to pick which element the response goes into. The simplest way is to give that element an id, and point to it with a CSS selector:

<button hx-get="/todos/" hx-target="#todo-list" hx-swap="beforeend">
    Load more
</button>

<div id="todo-list">
    ...
</div>

When you click the button, HTMX fetches /todos/ and appends the HTML it gets back to the end of #todo-list.

Learn more