AI Hints
Home›JavaScript Tutorial›Events and Forms
JavaScript · Lesson 99 of 138

Practice: A Counter App

Buttons and state.

⏱ 2 min read▶ Video at 1:58:18🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Let's build a small app. A counter with three buttons, plus, minus, and reset. It shows a pattern used in almost every interactive page. Keep your data in a variable, and write one function that draws the page from that data.

Practice: A Counter App
From the video: Practice: A Counter App
  • A counter app
  • Plus, minus, reset
  • Data, then draw

State and render

The count is our state, the data the app depends on. Render draws the page from the state, and colours it by sign. Each button changes the state, then calls render. One listener handles all three buttons, using a data attribute. We clicked plus twice, then minus five times, so the count is minus three.

index.htmlpython
<link rel="stylesheet" href="style.css">
<p id="out" class="big">0</p>
<button data-step="1" id="plus">+1</button>
<button data-step="-1" id="minus">-1</button>
<button data-step="0">Reset</button>
<script>
  let count = 0;
  const out = document.querySelector("#out");
  function render() {
    out.textContent = count;
    out.style.color = count < 0 ? "crimson" : count > 0 ? "seagreen" : "";
  }
  document.body.addEventListener("click", (e) => {
    const step = e.target.dataset.step;
    if (step === undefined) return;
    count = step === "0" ? 0 : count + Number(step);
    render();
  });
</script>
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#f7df1e;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"click": "#plus", "times": 2}, {"click": "#minus", "times": 5}]

The pattern

Keep the state in one place. Change it only in event handlers. And after every change, call render. Because the page is always drawn from the state, it can never get out of step with it. Frameworks like React are built around this same idea.

keyvalue
Statethe data
Eventschange the state
render()draw from the state
data-*extra info on elements

Summary

Keep state in variables, change it in event handlers, and redraw with a render function. Next, a to do list, built the same way.

Key takeaways
  • State
  • Events change it
  • render() draws it
Next up: Practice: A To-Do List — add, tick, delete