AI Workshop: learn to build apps with AI →
htmx: Conditionally hide HTML elements based on HTMX request status

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


HTMX lets us create an HTTP request pretty easily using hx-get or hx-post, etc.

The request lifecycle goes through a set of stages: settling, request, swapping, added (see https://htmx.org/docs/#request-operations)

Each time the state changes, HTMX adds a class to the element:

  • htmx-indicator
  • htmx-added
  • htmx-settling
  • htmx-swapping

You can target those classes with CSS to add transitions or whatever to the elements based on the state of the request.

Using Tailwind CSS, you can use a “trick” to style those with variants.

You can configure variants in your tailwind.config.js file:

//...
  plugins: [
    plugin(function({ addVariant }) {
      addVariant('htmx-settling', ['&.htmx-settling', '.htmx-settling &'])
      addVariant('htmx-request', ['&.htmx-request', '.htmx-request &'])
      addVariant('htmx-swapping', ['&.htmx-swapping', '.htmx-swapping &'])
      addVariant('htmx-added', ['&.htmx-added', '.htmx-added &'])
    }),
  ],
//...

Now you can use those variants like this:

<button class="htmx-added:opacity-0 opacity-100 transition-opacity duration-1000">
  click this
</button>

Lessons in this unit:

0: Introduction
1: Why htmx
2: The core idea of htmx
3: Installing htmx
4: Doing a GET request
5: Swap
6: POST request
7: Targets
8: Loading indicator
9: Confirming actions, and prompts
10: Triggers
11: Request headers
12: Response headers
13: Events
14: Redirect after request
15: Send files using htmx.ajax()
16: Perform something on page load
17: ▶︎ Conditionally hide HTML elements based on HTMX request status
18: htmx + Alpine template tag
19: htmx, include hidden input fields outside of a form
20: htmx trigger request via JS event