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:
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>
I wrote 21 books to help you become a better developer:
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- TypeScript Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux Commands Handbook
- C Handbook
- JavaScript Handbook
- Svelte Handbook
- CSS Handbook
- Node.js Handbook
- Vue Handbook