Progress Bar

Demonstrates a job-runner like progress bar

Back | Explain | Code | Htmx Docs
This example shows how to implement a smoothly scrolling progress bar. We start with an initial state with a button that issues a POST to /start to begin the job: ``` @app.get def page(): return Div(hx_target="this", hx_swap="outerHTML")( H3("Start Progress"), Button("Start Job", hx_post=start.rt(), cls="btn primary"), ) ``` This progress bar is updated every 600 milliseconds, with the “width” style attribute and aria-valuenow attributed set to current progress value. Because there is an id on the progress bar div, htmx will smoothly transition between requests by settling the style attribute into its new value. This, when coupled with CSS transitions, makes the visual transition continuous rather than jumpy. ``` @app.post def start(): global current current = 1 return Div(hx_trigger="done", hx_get=job_finished.rt(), hx_swap="outerHTML", hx_target="this")( H3("Running", role="status", id="pblabel", tabindex="-1", autofocus=""), Div(hx_get=progress_bar.rt(), hx_trigger="every 600ms", hx_target="this", hx_swap="innerHTML")( progress_bar(), ), ) @app.get def progress_bar(): global current if current <= 100: current += 20 return Div(cls="progress")( Div(style=f"width:{current - 20}%", id="THIS_ID_IS_INDISPENSIBLE", cls="progressbar"), ) return HttpHeader("HX-Trigger", "done") ``` Finally, when the process is complete, a server returns HX-Trigger: done header, which triggers an update of the UI to “Complete” state with a restart button added to the UI: ``` @app.get def job_finished(): return Div(hx_swap="outerHTML", hx_target="this")( H3("Complete", role="status", id="pblabel", tabindex="-1", autofocus=""), Div(Div(style="width:100%", id="THIS_ID_IS_INDISPENSIBLE", cls="progressbar"), cls="progress"), Button("Restart Job", hx_post=start.rt(), cls="btn primary show"), ) ```

Direct url