← Web basics: HTML, CSS and JavaScript
Project: a click counter
Plus, minus and reset buttons that keep a number in sync.
A counter is the "hello world" of interactive pages. Keep the current number in a let variable, and write one small function that shows it on the page. Each button's click listener changes the variable and then calls that function. Keeping the number in a variable (your "state") and the page as a display of it is the same idea big apps use, just smaller.
let count = 0;
const countBox = document.querySelector("#count");
function show() {
countBox.textContent = count;
}
document.querySelector("#plus").addEventListener("click", () => {
count = count + 1;
show();
});The plus button changes the state (count) and then refreshes the display. Adding minus and reset buttons follows the same pattern.
Rules belong in the state change: if the count must never go below 0, check that before subtracting.
Reading the number back from the page with Number(countBox.textContent) also works, but a variable is simpler and safer.