Skip to content

Conditionally hide HTML elements based on HTMX request status

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:

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>

I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook

JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list