Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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. 1

    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.

  2. 2

    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.

Back

6/10

  1. 1. JavaScript in a Web Page
  2. 2. Finding Elements
  3. 3. When Nothing Is Found
  4. 4. Changing Styles
  5. 5. Reacting to Clicks
  6. 6. A Click Counter
  7. 7. Text Fields
  8. 8. Creating Elements
  9. 9. Showing an Array
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.