Below is a working example of how a JavaScript click event functions. Click the button to see it in action!
// 1. Select the elements from the HTML page
const button = document.getElementById('my-button');
const output = document.getElementById('output');
// 2. Create a variable to keep track of state
let clickCount = 0;
// 3. Add the Event Listener
button.addEventListener('click', () => {
// This code only runs when the button is actually clicked!
clickCount++;
output.textContent = `Total clicks: ${clickCount}`;
button.textContent = "Clicked again!";
});
document.getElementById() to find the specific button
and the text-output `div` on the page so JavaScript knows what to manipulate.clickCount starting at 0 to
remember how many times the button is clicked..addEventListener('click', ...) to the button. This
tells the browser: "Whenever this button receives a click, run the function inside!".