javascript
HTMX - Show loader when request is in progress
January 28, 2023
In HTMX, you can use the hx-get or hx-post attribute to make an AJAX request, and the hx-indicator attribute to toggle the visibility of a loader element.
<button hx-get="/get-data">
Click Me!
<img class="htmx-indicator" src="/loading.gif">
</button>
Show loader when request is in progress in HTMX
To show a loader when an HTMX ajax request is in progress:
- Create a loading screen or element that you want to show while loading and assign an id attribute to it.
- Use hx-indicator attribute and assign the above id to it to show the loading element when the ajax request is in progress.
Show indicator using htmx-indicatior class attribute:
<button hx-get="/get-data">
Click Me!
<img class="htmx-indicator" src="/loading.gif">
</button>
Show indicator using id and hx-indicator attribute:
<div>
<button hx-get="/get-data" hx-target="reponse_data" hx-indicator="#loader">
Click Me!
</button>
<div id="reponse_data'"></div>
<img id="loader" class="htmx-indicator" src="/spinner.gif"/>
</div>
In this example, the hx-get attribute makes a GET request to the URL '/get-data' and updates the element with the ID 'reponse_data' with the response. The hx-indicator attribute is used to toggle the visibility of the loader element with the ID 'loader' while the request is in progress.
Or you are using form then you can use the below code example:
<form hx-post="/submit-form" hx-target="#response" hx-indicator="#indicator">
<label>Name: <input type="text" name="name"></label>
<label>Email: <input type="email" name="email"></label>
<input type="submit" value="Submit">
<img id="indicator" class="htmx-indicator" src="/loading.gif"/>
</form>
<div id="response"></div>
Was this helpful?
Similar Posts
- HTMX - Send a Post request on Form Submit
- Show data values on charts created using chart.js
- Show vertical line on data point hover Chart.js
- Show confirmation alert before submitting a form in Javascript
- xhr post request with form data javascript
- JQuery Ajax post request with form data
- Send Form Data in axios POST request