JavaScript Click Event Demo

Below is a working example of how a JavaScript click event functions. Click the button to see it in action!

Total clicks: 0

How does this work?

// 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!";
});

Code Breakdown: