Update a progress bar in JavaScript
Intermediate · 4 min read
File uploads, installers, quizzes and checkout steps all show a progress bar: a strip that fills up as the work gets done. Drawing one is a single line of JavaScript. Making it behave when it's handed a bad number, and making the number readable to people who can't see the bar, takes a little more.
In this tutorial you will write a setProgress function that sets a bar's width from a percentage, keeps the value between 0 and 100, copes with input that isn't a number, and tells screen readers the current value. You should know what a function is and have set an element's style before.
How the bar is drawn
The bar is two divs: an outer track and an inner fill. The fill's width is a percentage of the track, so width: 35% means 35% done.
<div id="track" role="progressbar" aria-valuemin="0" aria-valuemax="100"
aria-valuenow="0" aria-label="Upload progress">
<div id="fill"></div>
</div>
#track { border: 1px solid #8e8e98; border-radius: 999px; height: 1rem; overflow: hidden; background: #f2f2f4; }
#fill { height: 100%; width: 0; background: #3055d8; }
What the attributes on the track do
A screen reader (software that reads the page aloud) can't see how wide the fill is. These attributes tell it:
role="progressbar"says what the element is.aria-valueminandaria-valuemaxgive the range, here 0 to 100.aria-valuenowis the current value. This is the one your code has to keep updating.aria-labelgives the bar a name, so the user hears "Upload progress, 35 percent" and not just a number.
Here is the exercise. Try it on your own first, or read on and we will build it together.
8 A progress bar that updates
fairSet a bar's width from a completion percentage. Handle values outside 0–100, and make the value readable to a screen reader.
Stuck? Three hints, smallest first
- 1. Clamp with
Math.min(100, Math.max(0, value))before using it. - 2.
role="progressbar"witharia-valuenow,aria-valueminandaria-valuemax. - 3. The native
<progress>element does all of this without ARIA.
Step 1: the first version
const fill = document.getElementById('fill');
function setProgress(value) {
fill.style.width = `${value}%`;
}
setProgress(35);
console.log(fill.style.width); // 35%
setProgress(140);
console.log(fill.style.width); // 140%
It works for 35. But nothing stops 140, and a fill 140% wide spills past the end of the track. A negative number is worse: a width of -20% isn't valid CSS, so the browser ignores it and the bar keeps showing whatever it showed before. A stale bar is more misleading than an empty one.
Step 2: clamp the value
Clamping means "if it's too small, use the minimum; if it's too big, use the maximum". Math.max(0, n) gives the larger of 0 and n, so it lifts anything below 0 up to 0. Math.min(100, ...) then brings anything above 100 down to 100.
const clamp = (n) => Math.min(100, Math.max(0, n));
console.log(clamp(35), clamp(140), clamp(-20)); // 35 100 0
Step 3: input that isn't a number
The value often arrives as text, for example from an HTML attribute. Number() turns text into a number, but text that isn't a number becomes NaN, which means "not a number". And NaN gets straight through the clamp:
const clamp = (n) => Math.min(100, Math.max(0, n));
console.log(Number('42')); // 42
console.log(clamp(Number('abc'))); // NaN
console.log(clamp(Number('abc') || 0)); // 0
Math.max and Math.min give NaN if any input is NaN, so the width would become the string NaN%, which the browser also ignores. || 0 fixes it: NaN counts as false, so NaN || 0 gives 0.
Step 4: the full setProgress
const fill = document.getElementById('fill');
const track = document.getElementById('track');
function setProgress(value) {
const pct = Math.min(100, Math.max(0, Number(value) || 0));
fill.style.width = `${pct}%`;
track.setAttribute('aria-valuenow', String(pct));
return pct;
}
for (const v of [0, 35, 100, 140, -20, 'abc', '42']) {
console.log(v, '->', setProgress(v));
}
console.log(fill.style.width, track.getAttribute('aria-valuenow')); // 42% 42
The loop prints each input and what it became: 0, 35 and 100 stay as they are, 140 becomes 100, -20 and 'abc' become 0, and the text '42' becomes the number 42.
aria-valuenow is set from the same pct as the width, so what's drawn and what's announced always match. Returning pct lets the caller see the value that was actually used.
Step 5: buttons that set it
The live demo has preset buttons. Each one stores its value in a data-set attribute and passes it straight in:
const button = document.createElement('button');
button.setAttribute('data-set', '140');
button.addEventListener('click', () => setProgress(button.getAttribute('data-set')));
button.dispatchEvent(new Event('click'));
console.log(fill.style.width); // 100%
getAttribute returns the text '140', and setProgress turns it into a number and clamps it.
Step 6: the native element
HTML has a ready-made progress bar:
<progress max="100" value="35"></progress>
It needs no ARIA attributes and no clamping code. Build your own, as above, when you need a look the native element won't give you. Otherwise, progress is less code and harder to get wrong.
The full solution
The panel builds the bar and some preset buttons, then sets a range of values. Its checks confirm 0, 35 and 100 give those widths, 140 and -20 are clamped, 'abc' becomes 0 rather than NaN, a numeric string works, the announced value always matches the width, and the buttons set it too. Press Run, then try the buttons in the live demo.
allow-scripts only, so it cannot reach this page.const fill = el('div', { id: 'fill' });
const track = el('div', {
id: 'track', role: 'progressbar',
'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': '0',
'aria-label': 'Upload progress',
}, fill);
document.body.appendChild(track);
function setProgress(value) {
// Clamp first. A width of 140% overflows its container; a negative width is
// invalid and silently ignored, leaving the bar at whatever it was.
const pct = Math.min(100, Math.max(0, Number(value) || 0));
fill.style.width = `${pct}%`;
track.setAttribute('aria-valuenow', String(pct));
return pct;
}
const buttons = [0, 35, 100, 140, -20].map((v) => {
const b = el('button', { type: 'button', 'data-set': String(v) }, String(v));
b.addEventListener('click', () => setProgress(b.getAttribute('data-set')));
document.body.appendChild(b);
return b;
});
const width = () => fill.style.width;
const announced = () => track.getAttribute('aria-valuenow');
for (const v of [0, 35, 100, 140, -20, 'abc']) {
console.log(String(v).padEnd(5), '-> width', setProgress(v) + '%');
}
Output
16 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 16 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('zero gives no width', (() => { setProgress(0); return width(); })(), '0%');
test('35 gives 35%', (() => { setProgress(35); return width(); })(), '35%');
test('and announces 35', announced(), '35');
test('100 fills it', (() => { setProgress(100); return width(); })(), '100%');
test('above 100 is clamped', setProgress(140), 100);
test('so the bar cannot overflow', width(), '100%');
test('below 0 is clamped', setProgress(-20), 0);
test('to an empty bar', width(), '0%');
test('nonsense becomes 0 rather than NaN', setProgress('abc'), 0);
test('so the width is never the string NaN%', width().includes('NaN'), false);
test('a numeric string works', setProgress('42'), 42);
test('the announced value always matches the width', announced() + '%', width());
test('the range is declared', [track.getAttribute('aria-valuemin'), track.getAttribute('aria-valuemax')], ['0', '100']);
test('the bar has an accessible name', track.getAttribute('aria-label'), 'Upload progress');
test('clicking a preset button sets it', (() => { fire(buttons[1], 'click'); return width(); })(), '35%');
test('and the clamping button too', (() => { fire(buttons[3], 'click'); return width(); })(), '100%');
Clamping is the substance. Without it, a width above 100% overflows the container and a negative width is invalid CSS that the browser ignores — leaving the bar showing a stale value, which is worse than showing zero. Number(value) || 0 also catches NaN, since a width of "NaN%" is silently discarded the same way.
aria-valuenow has to move with the width, and the assertion comparing the two is there to keep them locked together. aria-valuemin, aria-valuemax and an accessible name complete the control.
Worth knowing that <progress max="100" value="35"> gives you all of this natively, with no ARIA and no clamping code, and the demo shows both. Build it by hand when you need appearance the native element will not give you; otherwise the native one is less code and harder to get wrong.
Common mistakes
- Not clamping. Above 100 the fill overflows, and below 0 the browser ignores the width and the bar shows an old value.
- Forgetting
NaN.Number('abc')isNaN, andNaNpasses throughMath.minandMath.max. Add|| 0. - Updating the width but not
aria-valuenow. The bar moves on screen while a screen reader keeps announcing 0.
Try it yourself
- Show the percentage as text next to the bar, such as "35%", updated in
setProgress. - Use
setIntervalto callsetProgresswith 0, 10, 20 and so on up to 100, one step every 200 milliseconds, then stop. - Add
transition: width .2s easeto the fill, and turn it off inside@media (prefers-reduced-motion: reduce).