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
- Create a variable
countthat starts at0. - When the button with the id
addis clicked, increasecountby 1 and show it in the element with the idcount. - When the button with the id
resetis clicked, setcountback to 0 and show that too. - Click the buttons in the preview to test your code.
- The script uses
addEventListenerfor the click events - Clicking Add Visitor three times shows
3 - Clicking Reset shows
0again - After a reset, counting starts from 1 again