Global Loading Spinner Using HTMX & Bootstrap 5

What HTMX Does During a Request

As stated in the HTMX documentation:

The htmx-request class is applied to the appropriate elements.

Additionally, the documentation mentions:

If you want the htmx-request class added to a different element, you can use the hx-indicator attribute with a CSS selector to do so.

To achieve this, we have two options:

  1. Specify the hx-indicator attribute on any element that triggers an HTMX request.
  2. Wrap all content in a parent element (e.g., a <div>) and specify the hx-indicator attribute on it. This works because the hx-indicator value is inherited by all child elements.

In this guide, we will use the second option.

Using Bootstrap's Spinner

We will customize Bootstrap's spinner to act as a global loading indicator.

<!-- Loading spinner -->
<div class="loader">
    <div class="spinner-border text-dark" role="status">
        <span class="visually-hidden">Loading...</span>
    </div>
</div>
<!-- End of loading spinner -->

<!-- Content wrapper -->
<div hx-indicator=".loader">
    <!-- Content goes here -->
</div>
<!-- End of content wrapper -->

Notice that the value of hx-indicator is a CSS selector.

When there is no HTMX request, the loader should remain hidden. To achieve this, we set its display property to none:

.loader {
    display: none;
}

When an HTMX request is issued, the loader should appear at the center of the screen. It should be both vertically and horizontally centered. Here's the CSS for that:

.htmx-request.loader {
    display: inline;
    position: fixed;
    z-index: 9999;
    width: 100px;
    height: 100px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

.htmx-request.loader div {
    height: 100%;
    width: 100%;
}

And voilĂ ! Here is the result of our simple loading spinner:

Loading spinner demo

That's it for now. For the full code, you can visit my GitHub repository here.

Unfortunately, the demonstration link on Heroku is no longer functional since Heroku no longer offers free hosting.

External Links

Here are some useful links for other HTMX use cases (to be updated soon):