Multi-step task
A task in a few steps: where you are, the step in hand and the way on and back.
A multi-step task asks for a few things in order: the progress says where the reader is, one step is in hand, and its actions lead on and back. The frame is a page, so the document scrolls as a whole and the actions sit at the end of the form, in its flow. The example sets up a workspace in three steps and keeps what is typed in the page's own memory.
Multi-step task
<div class="page bg-surface-base fg-text-body text-sm" data-example="multi-step"> <header class="navbar" style="--navbar-padding-x: max(1.5rem, calc(50% - 26rem))"> <a class="navbar-brand" href="#"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <circle cx="8" cy="8" r="6" /> <path d="M8 4.3333A3.6667 3.6667 0 0 1 8 11.6667Z" fill="currentColor" stroke="none" /> </svg>Atlas</a> <a class="btn btn-quiet btn-sm ml-auto shrink(1)" href="#">Save and exit</a> </header> <main class="grow(1) w-full max-w(880) mx-auto px-lg pt-xl pb-2xl container-inline"> <header class="flex flex-col gap-3xs mb-xl"> <h1 class="heading heading-xl">Set up your workspace</h1> <p class="m(0) fg-text-muted">Three steps, about two minutes. Everything here can be changed later in settings.</p> </header> <nav class="mb-xl max-w(560) hidden@container(--3xl)" aria-label="Progress"> <ol class="steps" data-ms-progress="short"> <li class="steps-item basis-auto"> <a class="steps-title link link-quiet" href="#ms-details">Basic details</a> </li> <li class="steps-item basis-auto"> <a class="steps-title link link-quiet" href="#ms-preferences">Preferences</a> </li> <li class="steps-item basis-auto"> <span class="steps-title">Review</span> </li> </ol> </nav> <div class="flex gap-2xl items-start"> <nav class="w(224) shrink(0) sticky top(72) hidden block@container(--3xl)" aria-label="Progress"> <ol class="steps steps-vertical" data-ms-progress> <li class="steps-item"> <span class="steps-body"> <a class="steps-title link link-quiet" href="#ms-details">Basic details</a> <span class="steps-description">Name, address and contact</span> </span> </li> <li class="steps-item"> <span class="steps-body"> <a class="steps-title link link-quiet" href="#ms-preferences">Preferences</a> <span class="steps-description">Alerts and region</span> </span> </li> <li class="steps-item"> <span class="steps-body"> <span class="steps-title">Review</span> <span class="steps-description">Check, then create</span> </span> </li> </ol> </nav> <div class="grow(1) basis(0) min-w(0) max-w(560)"> <div data-ms-task> <form class="form" method="post"> <section id="ms-details" data-ms-step aria-labelledby="ms-details-title"> <div class="form-fields"> <div class="flex flex-col gap-3xs"> <h2 class="heading scroll-mt(72)" id="ms-details-title" tabindex="-1"> <span class="sr-only">Step 1 of 3:</span>Basic details</h2> <p class="m(0) fg-text-muted">What the workspace is called and who answers for it.</p> </div> <div class="field"> <label for="ms-name">Workspace name</label> <input class="input" id="ms-name" name="name" autocomplete="organization" required pattern=".*\S.*" data-error="ms-name-error"> <span class="field-error" id="ms-name-error">Enter a name for the workspace.</span> </div> <div class="field"> <label for="ms-slug">Address</label> <div class="input-group"> <span class="input-group-addon">atlas.dev/</span> <input class="input-group-field" id="ms-slug" name="slug" autocomplete="off" autocapitalize="none" spellcheck="false" pattern="[a-z0-9]+(-[a-z0-9]+)*" required aria-describedby="ms-slug-hint" data-error="ms-slug-error"> </div> <span class="field-hint" id="ms-slug-hint">Lowercase letters, numbers and hyphens.</span> <span class="field-error" id="ms-slug-error">Enter an address in lowercase letters, numbers and hyphens, such as atlas-labs.</span> </div> <div class="field"> <label for="ms-email">Contact email</label> <input class="input" id="ms-email" type="email" name="email" autocomplete="email" placeholder="you@company.com" required data-error="ms-email-error"> <span class="field-error" id="ms-email-error">Enter an email address, such as you@company.com.</span> </div> </div> </section> <section id="ms-preferences" data-ms-step aria-labelledby="ms-preferences-title"> <div class="form-fields"> <div class="flex flex-col gap-3xs"> <h2 class="heading scroll-mt(72)" id="ms-preferences-title" tabindex="-1"> <span class="sr-only">Step 2 of 3:</span>Preferences</h2> <p class="m(0) fg-text-muted">How Atlas reaches you, and where it builds.</p> </div> <fieldset class="fieldset gap-sm"> <legend class="fieldset-legend">Where should deployment alerts go?</legend> <div class="auto-grid auto-grid-fit gap-sm" style="--auto-grid-min: 11rem"> <label class="choice"> <input type="radio" class="radio" name="alerts" value="email" checked> <span class="choice-body"> <span class="choice-title">Email</span> <span class="choice-description">To the contact address, as each deployment fails.</span> </span> </label> <label class="choice"> <input type="radio" class="radio" name="alerts" value="phone"> <span class="choice-body"> <span class="choice-title">Phone</span> <span class="choice-description">A text message, for production only.</span> </span> </label> <label class="choice"> <input type="radio" class="radio" name="alerts" value="none"> <span class="choice-body"> <span class="choice-title">None</span> <span class="choice-description">Nothing is sent. Failures show in the dashboard.</span> </span> </label> </div> </fieldset> <div data-ms-phone> <div class="field"> <label for="ms-phone">Phone number</label> <input class="input" id="ms-phone" type="tel" name="phone" autocomplete="tel" pattern="\+?[0-9][0-9 \-]{6,}" aria-describedby="ms-phone-hint" data-error="ms-phone-error"> <span class="field-hint" id="ms-phone-hint">Needed only when alerts go to a phone. Include the country code.</span> <span class="field-error" id="ms-phone-error">Enter a phone number with its country code, such as +886 912 345 678.</span> </div> </div> <div class="field"> <label for="ms-region">Default region</label> <select class="select" id="ms-region" name="region" aria-describedby="ms-region-hint"> <option class="select-option" value="Tokyo (hnd1)">Tokyo (hnd1)</option> <option class="select-option" value="Singapore (sin1)">Singapore (sin1)</option> <option class="select-option" value="Frankfurt (fra1)">Frankfurt (fra1)</option> <option class="select-option" value="Washington, D.C. (iad1)">Washington, D.C. (iad1)</option> </select> <span class="field-hint" id="ms-region-hint">Where new projects are built and served.</span> </div> </div> </section> <section id="ms-review" data-ms-step data-ms-review aria-labelledby="ms-review-title" hidden> <div class="form-fields"> <div class="flex flex-col gap-3xs"> <h2 class="heading scroll-mt(72)" id="ms-review-title" tabindex="-1"> <span class="sr-only">Step 3 of 3:</span>Review</h2> <p class="m(0) fg-text-muted">Check what you entered, then create the workspace.</p> </div> <div class="flex flex-col gap-2xs"> <div class="flex items-center justify-between gap-sm"> <h3 class="heading heading-xs">Basic details</h3> <button type="button" class="btn btn-quiet btn-sm btn-hang-end" data-ms-edit="0">Edit <span class="sr-only">basic details</span> </button> </div> <dl class="data-list"> <div class="data-list-item"> <dt class="data-list-term min-w(128)">Workspace name</dt> <dd class="data-list-value" data-ms-value="name"></dd> </div> <div class="data-list-item"> <dt class="data-list-term">Address</dt> <dd class="data-list-value" data-ms-value="address"></dd> </div> <div class="data-list-item"> <dt class="data-list-term">Contact email</dt> <dd class="data-list-value" data-ms-value="email"></dd> </div> </dl> </div> <div class="flex flex-col gap-2xs"> <div class="flex items-center justify-between gap-sm"> <h3 class="heading heading-xs">Preferences</h3> <button type="button" class="btn btn-quiet btn-sm btn-hang-end" data-ms-edit="1">Edit <span class="sr-only">preferences</span> </button> </div> <dl class="data-list"> <div class="data-list-item"> <dt class="data-list-term min-w(128)">Deployment alerts</dt> <dd class="data-list-value" data-ms-value="alerts"></dd> </div> <div class="data-list-item"> <dt class="data-list-term">Default region</dt> <dd class="data-list-value" data-ms-value="region"></dd> </div> </dl> </div> </div> </section> <div class="form-actions"> <button type="button" class="btn hidden" data-ms-back>Back</button> <button class="btn btn-primary" data-ms-next>Create workspace</button> </div> </form> </div> <div data-ms-done hidden> <div class="flex flex-col items-start gap-md"> <span class="icon-frame icon-frame-success" aria-hidden="true"> <svg class="icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M3.5 10L7.8545 14.3545A0.2 0.2 0 0 0 8.1413 14.3504L16.5 5.5" /> </svg> </span> <div class="flex flex-col gap-3xs"> <h2 class="heading scroll-mt(72)" tabindex="-1" data-ms-done-title>Workspace created</h2> <p class="m(0) fg-text-muted"> <span class="fg-text-strong" data-ms-value="name"></span>is ready at <span class="fg-text-strong" data-ms-value="address"></span>. This example keeps what you typed in memory only: nothing was sent.</p> </div> <button type="button" class="btn" data-ms-restart>Start over</button> </div> </div> </div> </div> </main></div>/** * A workspace set up in three steps, with nowhere to send it. The markup is one whole form in order, which is * what a browser without this module shows. The module divides it: it shows one step at a time, moves * aria-current along the progress, checks the step in hand before going on, and at the end swaps the form * for the result. What was typed stays in the fields, and where the reader is stays in `state`; nothing is * stored and nothing leaves the page. In a product each step is a route and the server keeps the draft. * Returns the function that stops it and puts the whole form back. */export function mount(root) { const controller = new AbortController() const { signal } = controller const task = root.querySelector('[data-ms-task]') const form = task.querySelector('.form') const steps = [...form.querySelectorAll('[data-ms-step]')] const review = form.querySelector('[data-ms-review]') const back = form.querySelector('[data-ms-back]') const next = form.querySelector('[data-ms-next]') const done = root.querySelector('[data-ms-done]') const phone = form.querySelector('[data-ms-phone]') // The same three steps twice: the vertical list of a wide page and the short row of a narrow one. const lists = [...root.querySelectorAll('[data-ms-progress]')].map(list => ({ list, short: list.dataset.msProgress === 'short', items: [...list.querySelectorAll('.steps-item')] })) const last = steps.length - 1 const submitLabel = next.textContent // Where the reader is, the furthest step they have reached, and whether the task is finished. const state = { step: 0, reached: 0, done: false } /** * A step's name in the progress is a link while the step can be opened and plain words while it cannot, as * the steps component asks: the element is replaced only when that changes. */ const name = (item, index, open) => { const old = item.querySelector('.steps-title') if ((old.localName === 'a') === open) return old const title = document.createElement(open ? 'a' : 'span') title.className = open ? 'steps-title link link-quiet' : 'steps-title' title.textContent = old.textContent if (open) title.href = `#${steps[index].id}` old.replaceWith(title) return title } const headingOf = (step) => steps[step].querySelector('.heading') const controlsOf = (step) => [...steps[step].querySelectorAll('input, select, textarea')].filter(control => control.willValidate) /** * A field's error is read with the field only while it shows: its id joins aria-describedby, after the hint, * while the field is marked or the browser reports it, and leaves when the value is valid again. */ const describe = (control) => { if (!control.dataset?.error) return const invalid = !control.validity.valid && (control.getAttribute('aria-invalid') === 'true' || control.matches(':user-invalid')) if (control.validity.valid) control.removeAttribute('aria-invalid') const ids = (control.getAttribute('aria-describedby') ?? '').split(' ').filter(id => id && id !== control.dataset.error) if (invalid) ids.push(control.dataset.error) if (ids.length) control.setAttribute('aria-describedby', ids.join(' ')) else control.removeAttribute('aria-describedby') } /** * The browser holds the rules (required, type, pattern) and shows a field's error once the reader has edited * it. A field never touched has to be marked here, with aria-invalid, when Next is pressed: a submit would mark * every field of the form as tried, the ones in steps not reached yet among them. Focus goes to the first. */ const check = (step) => { const invalid = controlsOf(step).filter(control => !control.validity.valid) for (const control of invalid) { control.setAttribute('aria-invalid', 'true') describe(control) } if (!invalid.length) return true if (state.step !== step) { state.step = step render() } invalid[0].focus() return false } // The phone number is asked for, and required, only while alerts go to a phone. const askPhone = () => { const field = phone.querySelector('.input') const wanted = form.elements.alerts.value === 'phone' phone.hidden = !wanted field.disabled = !wanted field.required = wanted if (!wanted) field.removeAttribute('aria-invalid') // An error that no longer shows is no longer read with the field when it comes back. describe(field) } const values = () => { const written = new FormData(form) const text = (name) => String(written.get(name) ?? '').trim() const alerts = { email: `Email to ${text('email')}`, phone: `Text message to ${text('phone')}`, none: 'None' } return { name: text('name'), address: `atlas.dev/${text('slug')}`, email: text('email'), alerts: alerts[text('alerts')], region: text('region') } } const render = () => { task.hidden = state.done done.hidden = !state.done steps.forEach((step, index) => { step.hidden = index !== state.step }) // A button's own display outranks the hidden attribute, so Back leaves with the utility of that name. back.classList.toggle('hidden', state.step === 0) next.textContent = state.step === last ? submitLabel : 'Next' for (const { list, short, items } of lists) { list.classList.toggle('steps-complete', state.done) items.forEach((item, index) => { const current = !state.done && index === state.step // A step already reached is a link back to it; the current one and the ones ahead are plain words. const open = !state.done && !current && index <= state.reached if (current) item.setAttribute('aria-current', 'step') else item.removeAttribute('aria-current') // In the short row the other steps' names are not drawn, and a link nobody can see is not one to tab to or // to tap: there a step already reached is words, and Back is the way to it. const title = name(item, index, open && !short) // The short row shows the current step's name; the others keep theirs for assistive technology. if (short) title.classList.toggle('sr-only', !current) }) } // What was typed is set as text, never as markup. if (state.done || state.step === last) { const written = values() for (const slot of root.querySelectorAll('[data-ms-value]')) slot.textContent = written[slot.dataset.msValue] } } /** * Going on checks every step passed on the way and stops at the first that fails. Going back checks nothing: * a reader may leave a step half written and find it as they left it. */ const go = (target) => { for (let step = state.step; step < target; step++) if (!check(step)) return state.step = target state.reached = Math.max(state.reached, target) render() headingOf(target).focus() } const advance = () => { if (state.step < last) return go(state.step + 1) for (let step = 0; step < last; step++) if (!check(step)) return state.done = true render() done.querySelector('[data-ms-done-title]').focus() } next.addEventListener('click', advance, { signal }) back.addEventListener('click', () => go(state.step - 1), { signal }) // Next is not a submit button, so Enter in a field is given the same meaning here. form.addEventListener('keydown', (event) => { if (event.key !== 'Enter' || event.isComposing || !event.target.matches('input')) return event.preventDefault() advance() }, { signal }) form.addEventListener('submit', event => event.preventDefault(), { signal }) for (const type of ['input', 'change', 'focusout']) { form.addEventListener(type, event => describe(event.target), { signal }) } form.addEventListener('change', (event) => { if (event.target.name === 'alerts') askPhone() }, { signal }) // A step already reached is opened from the progress, and from Edit in the review. for (const { list, items } of lists) { list.addEventListener('click', (event) => { const title = event.target.closest('a.steps-title') if (!title) return event.preventDefault() go(items.indexOf(title.closest('.steps-item'))) }, { signal }) } for (const edit of form.querySelectorAll('[data-ms-edit]')) { edit.addEventListener('click', () => go(Number(edit.dataset.msEdit)), { signal }) } const clear = () => { form.reset() for (const control of form.querySelectorAll('[data-error]')) { control.removeAttribute('aria-invalid') describe(control) } Object.assign(state, { step: 0, reached: 0, done: false }) } root.querySelector('[data-ms-restart]').addEventListener('click', () => { clear() askPhone() render() headingOf(0).focus() }, { signal }) next.type = 'button' askPhone() render() return () => { controller.abort() clear() // The whole form again, in order, as the markup has it. task.hidden = false done.hidden = true steps.forEach((step) => { step.hidden = step === review }) back.classList.add('hidden') next.type = 'submit' next.textContent = submitLabel phone.hidden = false phone.querySelector('.input').disabled = false phone.querySelector('.input').required = false for (const { list, items } of lists) { list.classList.remove('steps-complete') items.forEach((item, index) => { item.removeAttribute('aria-current') // The review holds no field, so the whole form has nothing to link its step to. name(item, index, steps[index] !== review).classList.remove('sr-only') }) } }}#How it is built
- A page with a task header. The navbar holds the brand and one way out, a quiet "Save and exit" pushed to the far end with
ml-auto. A task has no main navigation: every other link is a way to lose the work. - One measure for the task. The main region is
max-w(880) mx-auto px-lgand a size container,container-inline. That leaves 832px: a progress column ofw(224), agap-2xlof 48px and a form ofmax-w(560), which is as wide as one column of fields reads well. - Steps for the progress. Only the current item carries
aria-current="step"; the stylesheet draws the steps before it complete and the ones after it waiting. The name of a step that can be opened is a quiet link, and the others are plain words. - One form for the whole task. Each step is a
<section>named by its heading, with its fields inform-fields, so they keep the form's distance of 1.25rem. The options of the second step are the choice cards block: a<fieldset>whose legend is the question, and an auto grid of choices that stand three across in the form's column and one under another on a phone. form-actionsat the end of the form. Back comes first in the source and the confirming button last. Below 24rem of form they stack at full width with the confirming one first, which is where a phone lands. Nothing is fixed to the foot of the viewport: a bar there covers the fields above it once a keyboard is open.- The review is a data list for each step, under the step's name and an Edit button that opens it. The button is quiet and takes
btn-hang-end, so its word ends on the edge the values run to.
#The progress at each width
The page holds the progress twice, and shows one.
- From 48rem of main region it is a
steps steps-verticallist beside the form: each step has its name and a line on what it asks for. The list issticky top(72), 16px under the 56px navbar, so it stays in view while a long step scrolls. - Below 48rem it is one row of
stepsover the form. The row shows the name of the current step only; the names of the other two aresr-only, so the markers and the lines carry the position and every name is still read out.
hidden@container(--3xl) is on the row and hidden block@container(--3xl) on the column. The one that is away is display: none, so assistive technology and the keyboard meet a single progress.
A row of steps with all three names does not fit a phone: the component cuts a name that has no room with an ellipsis. With one name the row is whole at 390px. Each item of the row is basis-auto, so the current step takes the room its name needs and the other two share the rest. On a phone at twice the text size even that one name is cut; the heading under the row says it in full.
#What the script decides
The markup is the whole form in order: both steps of fields, then one button that sends it. The example's module is what divides it into steps, and it is short because the browser and the stylesheet do most of the work.
- The browser holds the rules.
required,type="email"andpatternsay what a valid value is, and the module only readsvalidity.valid. Each field has its message in afield-error, which the input stylesheet shows while the field is invalid and hides again when it is not. :user-invalidshows an error once the reader has edited a field. That needs no script. A field never touched is another matter: Next setsaria-invalid="true"on every field of the step that fails, which draws the same state, and takes it off as each value becomes valid.- Next is a button, not a submit. A submit attempt marks every field of a form as tried, the fields of steps not reached yet among them, and they would open already in error. So the module checks the step in hand itself, and gives Enter in a field the same meaning as Next.
- Focus follows the reader. When a step fails, focus goes to its first invalid field. When the step changes, focus goes to the new step's heading, which names the step and its place: "Step 2 of 3: Preferences".
- Going back checks nothing. Back, a step's name in the progress and Edit in the review all leave the current step as it is, even half written, and every field keeps its value because it never leaves the document. Going on checks each step on the way and stops at the first that fails. A step not reached yet is not a link, so it cannot be jumped to.
- A field that depends on an answer. The phone number is shown, and required, only while alerts go to a phone. While it is away it is
disabled, so it is neither checked nor sent.
In a product, most of this belongs to the router and the server:
- A route for each step, such as
/setup/detailsand/setup/preferences. Each step is then a form of its own, Next is its submit button, and the browser's Back and a reload do what the reader expects. The progress links are real links to those routes. - The server validates every step again and answers with the errors it found. Show them the same way:
aria-invalid="true"on the field and the message in itsfield-error. - The server keeps the draft. Each Next saves what the step holds, "Save and exit" saves and leaves, and the review reads the draft back instead of the fields. The furthest step reached is part of the draft, and the server refuses a route beyond it.
#When to use it
Use steps when the order matters: a later step depends on an earlier answer, or the whole would be too much to take in at once. Three to five steps is the range; with more, ask whether some can wait until after the task.
- Use a settings page when the groups are independent and a reader comes back to change one of them. Its navigation lets them open any group in any order.
- Use a single form when everything fits one screen. Steps cost a reader the overview and a press for each part.
- Use a centered page for one short task with nothing before or after it, such as signing in.
#Accessibility
- The landmarks are the header, the main region and one navigation named "Progress". The step in hand is a
<section>named by its heading. - The progress is an
<ol>, so the list says how many steps there are, and the current one carriesaria-current="step". In the short row the names that are not shown are still in the list. - After a step changes, focus is on its heading, which has
tabindex="-1"andscroll-mt(72)so it is not left under the sticky navbar. A screen reader reads the step's place and name from there, and Tab goes to its first field. - When a step fails, focus is on the first invalid field. The field's
field-erroris added to itsaria-describedbywhile it shows, so the message is read with the label. - At the end, focus goes to the heading of the result, and "Start over" clears the fields and returns to the first step's heading.
- Without the script the page is one long form: both steps of fields are in the markup and none is
hidden, the phone number explains when it is needed, and the button sends everything at once. Only Back, the review and the result, which hold no field, start hidden.
#Related
- StepsWhere a reader is in a short sequence.
- FormThe rhythm of a form: rows, sections and actions that follow their column.
- InputText fields cut into the surface, with labels, hints, errors and groups.
- ChoiceA radio or checkbox option large enough to explain itself.
- RadioA small round well for one choice among several.
- SelectA native select whose option list is drawn in the same material.
- Auto gridAs many equal columns as fit, counted by the grid itself.
- Data listThe facts about one thing, as terms and values.
- NavbarThe bar at the top of a page, which takes its material once content scrolls under it.
- ButtonA raised control that lifts on hover and sinks when pressed.
- LinkText that goes somewhere, in the ink of its sentence.
- HeadingA title in the ink of the page, with the line over it and the paragraph under it.
- Icon frameA small well that holds an icon at its size beside a heading.