Building an unobtrusive HTMX Loading Indicator in 22 Lines of CSS
In this tutorial, we'll build the subtle loading indicator you see at the top of this page, using just 22 lines of CSS. This indicator automatically displays whenever a HTMX request is in progress.
Feel free to turn off the demo loading indicator with this toggle:
Step 1: Register the Custom Indicator with HTMX
To start, we need to define the loading indicator in our HTML by adding a custom indicator element within the <body>
tag.
Use the hx-indicator
attribute to tell HTMX which element will act as the loading indicator.
<body hx-indicator=".hx-loading-indicator">
<div class="hx-loading-indicator"></div>
...
</body>
This configuration tells HTMX to display the .hx-loading-indicator
element whenever a request is triggered.
Step 2: Add CSS for the Loading Indicator
Next, let's style the loading indicator by adding the following CSS to the <head>
of your document:
CSS Breakdown
Here's a breakdown of the key parts of this CSS:
-
Fixed Positioning: The indicator stays at the top of the page even when the user scrolls, thanks to the
position: fixed
rule. - Gradient Background: A simple gradient alternating between transparent and black stripes creates a movement effect.
-
Loading Animation: The
opacity: 1
rule, combined with the.htmx-request
class, makes the indicator visible while a request is in progress. The animation slides the gradient from left to right continuously. -
Smooth Fade-In: The
fadeIn
animation gradually brings the indicator into view over two seconds for a smoother user experience.
Conclusion
That's it! With just a few lines of HTML and CSS, we've built a clean, unobtrusive loading indicator for HTMX requests. You can further customize this indicator by adjusting the CSS animations and styling as needed.
If you'd like to see a live demo, check out the loading indicator in action on BudgetFlow, a personal finance app built with Flask and HTMX.