JavaScript Basics · Lesson 12 of 13

Reacting to Clicks

Interactive pages wait for something to happen, a click, a key press or a form being sent, and then react. Each of these happenings is called an event.

Listening for an event

addEventListener tells an element: when this event happens to you, run this function.

const button = document.querySelector("#hello");

button.addEventListener("click", () => {
  console.log("The button was clicked!");
});

It takes two things: the name of the event ("click") and a function to run. Here that is an arrow function with no parameters. The code inside does not run when the page loads. It runs each time the button is clicked.

Remembering things between clicks

A variable created outside the function keeps its value between clicks. That is how a counter works:

let likes = 0;
const output = document.querySelector("#likes");

button.addEventListener("click", () => {
  likes++;
  output.textContent = likes;
});

Reading a text box

The text someone typed into an <input> is in its value property:

const field = document.querySelector("#name");
console.log(field.value);

value is always a string, even when the box contains digits. Use Number(field.value) to calculate with it.

Other common events are "input" (the text in a field changed), "submit" (a form was sent) and "keydown" (a key was pressed).

Your Task

  1. Create a variable count that starts at 0.
  2. When the button with the id add is clicked, increase count by 1 and show it in the element with the id count.
  3. When the button with the id reset is clicked, set count back to 0 and show that too.
  4. Click the buttons in the preview to test your code.
  • The script uses addEventListener for the click events
  • Clicking Add Visitor three times shows 3
  • Clicking Reset shows 0 again
  • After a reset, counting starts from 1 again