Sub topic 9
Navigation, Back Button, and Progress Indicators
This chapter assumes you have read the earlier chapters on form state and on modeling the flow as a state machine. You should know the steps array and the reducer with next and back actions. You should also know the basics of the browser History API (pushState and the popstate event).
Once a form has several steps, users need answers to three questions. Where am I? Where can I go? What happens to my answers if I move? The reducer already enforces that moving forward requires a valid step and moving back keeps values. This chapter covers the parts the user sees and touches: the Back and Next buttons, the browser's own Back button, and the progress indicator.
Principles for step navigation
Four rules cover most of the design decisions.
- Going back never destroys data. Values live in shared state, not inside each step's DOM. A step that unmounts must not take its answers with it.
- Going forward is gated by validation of the current step only. Do not block on errors in steps the user has not reached yet.
- The URL, the visible step, and the progress indicator always agree. If they can disagree, users will end up on a screen the interface does not describe.
- The user can always tell how much is left. An unknown length makes people abandon forms.
Buttons: Next, Back, and their labels
Place the primary action (Next, or Submit on the last step) where the user's eye ends after the last field. Style Back as a secondary action so it is not hit by accident.
- Label buttons with their effect. "Next" is acceptable. "Continue to review" is better on the step before review, because it says what comes next.
- Use
type="button"for Back so it never submits the form. A<button>inside a form defaults totype="submit", which is a common cause of a Back click that triggers validation. - Hide Back on the first step instead of disabling it. A disabled control with no explanation adds noise.
- Keep Next enabled even when the step is invalid, and show errors when it is pressed. Disabled buttons give no reason for being disabled and are skipped by some assistive technology.
The browser Back button
Many users will press the browser's Back button instead of your Back button. If your steps exist only in JavaScript state, the browser does not know they exist. A single history entry covers the whole flow, so pressing Back leaves the form and the user loses their place. Your saved values may survive, but the experience feels broken.
The fix is to give each step a history entry and listen for popstate:
- Call
history.pushStatewhen the user moves to a new step. - Use
history.replaceStatefor the first entry, so the initial load does not create a duplicate. - On
popstate, read the step from the URL and show it.
const steps = ["account", "details", "review"] as const;
type StepId = (typeof steps)[number];
function isStepId(value: string | null): value is StepId {
return steps.some((s) => s === value);
}
function stepFromUrl(): StepId {
const value = new URLSearchParams(location.search).get("step");
return isStepId(value) ? value : steps[0];
}
let furthest = 0; // index of the furthest step the user has validly reached
function render(step: StepId): void {
document.querySelectorAll<HTMLElement>("[data-step]").forEach((el) => {
el.hidden = el.dataset.step !== step;
});
const heading = document.querySelector<HTMLElement>(`[data-step="${step}"] h2`);
heading?.focus();
}
function goTo(step: StepId, mode: "push" | "replace" | "none"): void {
// Never show a step the user has not unlocked, for example from a pasted URL.
const allowed = steps[Math.min(steps.indexOf(step), furthest)];
furthest = Math.max(furthest, steps.indexOf(allowed));
if (mode !== "none") {
const url = new URL(location.href);
url.searchParams.set("step", allowed);
if (mode === "push") history.pushState({ step: allowed }, "", url);
else history.replaceState({ step: allowed }, "", url);
}
render(allowed);
}
window.addEventListener("popstate", () => goTo(stepFromUrl(), "none"));
goTo(stepFromUrl(), "replace");The goTo function clamps the requested step to furthest. Without this clamp, someone who opens ?step=review directly, or restores a tab from an old session, lands on a step whose earlier data does not exist. When you add draft saving, restore furthest from the saved draft so a reload resumes correctly.
Note that popstate does not fire for pushState calls. You call render yourself in that case, which goTo does.
Forward history after Back
After the user presses browser Back twice and then submits a new step, the forward history entries are discarded. This is standard browser behavior and is fine. The values stay in your state, so nothing is lost.
Deciding which steps a user may visit
Navigation freedom is a design choice with trade-offs.
| Model | Behavior | Good for | Risk |
|---|---|---|---|
| Strictly linear | Only Next and Back | Short flows, checkout | Fixing an early mistake means many clicks |
| Visited steps only | Any step already reached can be clicked | Most multi-step forms | Needs the `furthest` bookkeeping shown above |
| Fully free | Any step at any time | Settings wizards, long applications | Steps may depend on each other, so validity is harder to track |
For the middle model, the rule is simple: a step is reachable if its index is at most furthest. If the user goes back and changes an answer that affects later steps (for example switching delivery from "ship" to "pickup"), later steps can become stale. Two safe responses are available:
- Lower
furthestto the changed step, so the user must pass through the later steps again. - Keep
furthestbut re-validate the affected later steps and mark them as needing attention.
The first is simpler and is what most flows should choose.
Progress indicators
A progress indicator tells the user the length of the flow and their position in it. Choose the form that fits the flow.
- Text only ("Step 2 of 4"). The simplest option, and it works well on small screens.
- Named step list. Shows labels such as Account, Details, Review. Best when users may jump between visited steps.
- Bar. Shows a percentage. Use it only when steps are similar in effort, because a bar that jumps from 25% to 90% misleads.
Always include text, even if you also show a bar or dots. Color and shape alone are not enough for users who cannot see them.
A named step list should be an ordered list, because the order carries meaning. Mark the current step with aria-current="step":
<nav aria-label="Progress">
<p>Step 2 of 3: Details</p>
<ol>
<li><a href="?step=account">Account <span class="visually-hidden">(completed)</span></a></li>
<li><a href="?step=details" aria-current="step">Details</a></li>
<li>Review <span class="visually-hidden">(not yet available)</span></li>
</ol>
</nav>The completed step is a link, the current step is marked, and the unreachable step is plain text. Showing unreachable steps as non-links keeps keyboard users from tabbing to controls that do nothing. The visually-hidden class is a common utility that hides text visually but leaves it available to screen readers. You must define it in your CSS.
Counting steps when fields are conditional
Conditional fields can change how many steps exist. If choosing "pickup" removes the shipping-address step, the indicator should recompute from the list of active steps, not from the fixed array. Otherwise the user sees "Step 2 of 4" change to "Step 2 of 3" with no explanation, or worse, sees a step number skipped. Derive the visible step list from the current values, as you did with activeValues, and compute "N of M" from that list. When the total changes after an answer, say so near the control that caused it.
Leaving the flow and unsaved changes
Users close tabs and click links. If a form holds meaningful unsaved input, consider the beforeunload event to warn them.
function guardUnsavedChanges(isDirty: () => boolean): void {
window.addEventListener("beforeunload", (event) => {
if (isDirty()) event.preventDefault();
});
}Browsers show their own generic message and ignore custom text. Use this guard sparingly. If you already save drafts, you may not need it at all, because nothing is lost. Do not attach it when the form is clean, or users learn to dismiss it.
Moving focus on step change
When the step changes, the old content disappears and the new content appears. Sighted mouse users see this, but keyboard and screen reader users can be left with focus on a removed button. The render function above moves focus to the new step's heading. For that to work, the heading needs tabindex="-1" so it can receive focus from a script without joining the tab order.
<section data-step="details" hidden>
<h2 tabindex="-1">Your details</h2>
</section>The accessibility chapter returns to this with live regions and announcements. For now, the minimum is that every step change moves focus to a known place.
Common mistakes
- Back button submits the form. The button lacks
type="button". - Steps without history entries. Browser Back exits the flow.
- A history entry per keystroke. Push on step change only.
- Trusting the URL. A pasted
?step=reviewshows a step with missing data. Clamp it. - Progress that moves on click, not on success. Advance the indicator only after validation passes.
- Errors from later steps on Next. Validate only the current step.
Exercise
A user on step 3 of 3 presses the browser Back button. Your app uses history.pushState on each step change and a popstate listener. They then paste the URL ?step=review into a new tab in a fresh session with no saved draft. What should the app show, and which line of the example enforces it?
Show answer
It should show the first step, "account". In goTo, the line const allowed = steps[Math.min(steps.indexOf(step), furthest)] clamps the requested step to furthest, which is 0 in a fresh session. The URL is then rewritten to the allowed step through replaceState or pushState, so the address bar matches what is displayed.
Exercise
A checkout form has the steps Account, Shipping, Payment, and Review. Choosing "pickup" removes the Shipping step. Describe how the progress indicator should behave and how you would implement the step count.
Show answer
The indicator should list only the active steps (Account, Payment, Review) and show "Step 2 of 3" when the user is on Payment. Implement it by deriving the visible step list from the current values, using each step's visibility rule, instead of from the fixed steps array. Compute "N of M" from that derived list, and tell the user near the delivery choice that the Shipping step was removed.