A Click Counter
A handler often needs to remember something from one click to the next, for example how many times a button was clicked. The page shows things, but it's the variables in your program that remember them. Here's a counter of the glasses of water you've drunk today:
const countText = document.querySelector("#count");
const drinkButton = document.querySelector("#drink");
let glasses = 0;
drinkButton.addEventListener("click", function () {
glasses++;
countText.textContent = glasses;
});On each click, the handler first changes the variable and then shows its new value on the page. textContent turns the number into text by itself.
The variable is created with let, because its value changes, and outside the function. Why not inside? A variable created inside a function exists only while the function runs, and each click runs the function anew. With let glasses = 0; inside the handler, every click would start from 0 again, and the page would show 1 forever.
Remember this pattern, because you'll use it all the time: the data lives in variables. When something happens, change the variables and then show them on the page.
Instructions
Create a variable cookies with the value 0. When eatButton is clicked, increase cookies by 1 and show its value in countText. Try clicking a few times.
When resetButton is clicked, set cookies back to 0 and show it in countText. The counting must then start again from 0: the next click on Eat a cookie shows 1.
Start programming for free
6/10