Project: Counter

Updated · 8 min read

This first project builds a small but complete interactive component: a counter for the number of payment installments a family chooses, from 1 to 12. It is deliberately simple, so the focus stays on the habits every project in this module uses: HTML first, state in one place, a render function that draws the page from state, event listeners that only dispatch changes, keyboard and screen reader support, and saving to storage. By the end you'll have a component you could drop into a real page.

What You'll Build

  • A value between 1 and 12, shown large in the middle.
  • Minus and plus buttons that are disabled at the limits.
  • A Reset button.
  • Keyboard shortcuts: Up and Down arrows change the value when the counter has focus.
  • A live region that tells screen reader users the new value.
  • The value is saved, so it survives a reload, and the monthly amount is recalculated as it changes.

Step 1: The HTML

Start with meaningful, accessible HTML. Real <button> elements are focusable and keyboard-operable without any JavaScript, and <output> is the right element for a calculated value:

counter.html
<section class="counter" aria-labelledby="counter-title">
  <h2 id="counter-title">Number of installments</h2>
  <div class="controls">
    <button type="button" id="dec" aria-label="Fewer installments">−</button>
    <output id="value" aria-live="polite">1</output>
    <button type="button" id="inc" aria-label="More installments">+</button>
  </div>
  <p id="monthly">1 payment of $1,350.00</p>
  <button type="button" id="reset">Reset</button>
</section>

aria-label gives the symbol-only buttons spoken names. aria-live="polite" on the output tells screen readers to announce changes to it.

Step 2: State and Rules

All the component's data lives in one small state object, and the rules are pure functions that know nothing about the DOM:

rules.js▶ Try it
const MIN = 1;
const MAX = 12;
const YEARLY_FEE_CENTS = 135000;
 
const clamp = (n) => Math.min(MAX, Math.max(MIN, n));
const change = (state, delta) => ({ ...state, count: clamp(state.count + delta) });
const monthlyCents = (count) => Math.ceil(YEARLY_FEE_CENTS / count);
 
let state = { count: 1 };
state = change(state, +1);
state = change(state, +20);
console.log(state.count, monthlyCents(state.count));
state = change(state, -50);
console.log(state.count, monthlyCents(state.count));
Output
12 11250
1 135000

clamp keeps the value in range no matter what (even if a bug asked for +20). monthlyCents rounds up so twelve payments never fall short of the yearly fee. Because these are pure functions, they're trivial to test.

Step 3: Render from State

One function draws everything from the state: the number, the disabled buttons, the monthly amount. Event handlers never update the DOM directly; they change state and call render:

render.js
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
 
function render(state) {
  valueEl.value = String(state.count);
  decBtn.disabled = state.count <= MIN;
  incBtn.disabled = state.count >= MAX;
  const each = usd.format(monthlyCents(state.count) / 100);
  monthlyEl.textContent = state.count === 1 ? `1 payment of ${each}` : `${state.count} payments of ${each}`;
}

Step 4: Events and Keyboard Support

Buttons dispatch changes. For keyboard users, Up and Down arrows also work while focus is anywhere inside the counter, and Home and End jump to the limits:

events.js
function dispatch(delta) {
  state = change(state, delta);
  render(state);
  save(state);
}
 
decBtn.addEventListener("click", () => dispatch(-1));
incBtn.addEventListener("click", () => dispatch(+1));
resetBtn.addEventListener("click", () => dispatch(MIN - state.count));
 
section.addEventListener("keydown", (event) => {
  const deltas = { ArrowUp: +1, ArrowDown: -1, Home: MIN - state.count, End: MAX - state.count };
  if (!(event.key in deltas)) return;
  event.preventDefault();
  dispatch(deltas[event.key]);
});

Step 5: Save and Restore

Save the count after each change, and restore it on load, validating whatever comes back:

storage.js
const KEY = "feeTracker.installments";
 
function load() {
  const saved = Number(localStorage.getItem(KEY));
  return { count: Number.isInteger(saved) ? clamp(saved) : MIN };
}
const save = (s) => localStorage.setItem(KEY, String(s.count));

The Complete Component

Everything together, as one page. The checker clicks plus three times, presses End and then the Down arrow on the plus button, and finally clicks Reset:

counter-complete.html
<section class="counter" aria-labelledby="counter-title">
  <h2 id="counter-title">Number of installments</h2>
  <button type="button" id="dec" aria-label="Fewer installments">−</button>
  <output id="value" aria-live="polite">1</output>
  <button type="button" id="inc" aria-label="More installments">+</button>
  <p id="monthly"></p>
  <button type="button" id="reset">Reset</button>
</section>
<script type="module">
  const MIN = 1, MAX = 12, YEARLY_FEE_CENTS = 135000, KEY = "feeTracker.installments";
  const clamp = (n) => Math.min(MAX, Math.max(MIN, n));
  const change = (s, delta) => ({ ...s, count: clamp(s.count + delta) });
  const monthlyCents = (count) => Math.ceil(YEARLY_FEE_CENTS / count);
  const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });

  const section = document.querySelector(".counter");
  const [valueEl, decBtn, incBtn, monthlyEl, resetBtn] = ["#value", "#dec", "#inc", "#monthly", "#reset"].map((s) => document.querySelector(s));

  const load = () => { const n = Number(localStorage.getItem(KEY)); return { count: Number.isInteger(n) ? clamp(n) : MIN }; };
  const save = (s) => localStorage.setItem(KEY, String(s.count));
  let state = load();

  function render(s) {
    valueEl.value = String(s.count);
    decBtn.disabled = s.count <= MIN;
    incBtn.disabled = s.count >= MAX;
    const each = usd.format(monthlyCents(s.count) / 100);
    monthlyEl.textContent = s.count === 1 ? `1 payment of ${each}` : `${s.count} payments of ${each}`;
    console.log(`${valueEl.value} | ${monthlyEl.textContent} | dec disabled: ${decBtn.disabled}, inc disabled: ${incBtn.disabled}`);
  }

  function dispatch(delta) {
    state = change(state, delta);
    render(state);
    save(state);
  }

  decBtn.addEventListener("click", () => dispatch(-1));
  incBtn.addEventListener("click", () => dispatch(+1));
  resetBtn.addEventListener("click", () => dispatch(MIN - state.count));
  section.addEventListener("keydown", (e) => {
    const deltas = { ArrowUp: +1, ArrowDown: -1, Home: MIN - state.count, End: MAX - state.count };
    if (!(e.key in deltas)) return;
    e.preventDefault();
    dispatch(deltas[e.key]);
  });
  render(state);
</script>
Output
1 | 1 payment of $1,350.00 | dec disabled: true, inc disabled: false
2 | 2 payments of $675.00 | dec disabled: false, inc disabled: false
3 | 3 payments of $450.00 | dec disabled: false, inc disabled: false
4 | 4 payments of $337.50 | dec disabled: false, inc disabled: false
12 | 12 payments of $112.50 | dec disabled: false, inc disabled: true
1 | 1 payment of $1,350.00 | dec disabled: true, inc disabled: false

Look closely: the checker pressed End and then ArrowDown on the plus button, but there's no line for the ArrowDown. When End took the count to 12, the plus button became disabled, and a disabled button can't hold focus, so the arrow key had nowhere to go. That is exactly the problem described in the warning above, caught by a real browser. Making the whole <section> focusable (tabindex="-1") and moving focus to it when a button becomes disabled, or using aria-disabled instead of disabled, keeps keyboard users in control.

Testing the Logic

The rules were written as pure functions, so they can be tested without a page:

counter.test.js▶ Try it
import { test } from "node:test";
import assert from "node:assert/strict";
 
const MIN = 1, MAX = 12;
const clamp = (n) => Math.min(MAX, Math.max(MIN, n));
const monthlyCents = (count) => Math.ceil(135000 / count);
 
test("clamp keeps the count between 1 and 12", () => {
  assert.deepEqual([-5, 0, 1, 7, 12, 99].map(clamp), [1, 1, 1, 7, 12, 12]);
});
 
test("monthly payments always cover the yearly fee", () => {
  for (let n = MIN; n <= MAX; n++) assert.ok(monthlyCents(n) * n >= 135000, `count ${n}`);
});
Output
✔ clamp keeps the count between 1 and 12 (0.780667ms)
✔ monthly payments always cover the yearly fee (0.081709ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 4.057417

Practice

Challenge: Add a "step" option: holding Shift while clicking plus or minus changes the count by 3 instead of 1. Only the event handlers need to change. Here is the new dispatch logic, tested in isolation:

Show solution
step.js▶ Try it
const clamp = (n) => Math.min(12, Math.max(1, n));
const deltaFor = (direction, shiftKey) => direction * (shiftKey ? 3 : 1);
 
let count = 1;
for (const [direction, shift] of [[+1, true], [+1, true], [+1, false], [-1, true]]) {
  count = clamp(count + deltaFor(direction, shift));
}
console.log(count);
Output
5

In the page, the click handler becomes incBtn.addEventListener("click", (e) => dispatch(deltaFor(+1, e.shiftKey))).

Quick check: Counter project

3 questions
1Where does the counter's current value live?
2Why is clamp applied inside change rather than in the buttons?
3What does aria-live="polite" do on the output?

Key Takeaways

PieceJob
stateThe current count
change, clampPure rules
render(state)Draw the UI
dispatch(delta)Change state, render, save
load/savePersist between visits

Was this tutorial helpful?

Lesson 133 of 139