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
- 1
Create a variable
cookieswith the value0. WheneatButtonis clicked, increasecookiesby 1 and show its value incountText. Try clicking a few times. - 2
When
resetButtonis clicked, setcookiesback to0and show it incountText. The counting must then start again from 0: the next click on Eat a cookie shows 1.