Skip to content

HTML Tutorial HTML and JavaScript

Basic JavaScript Interaction: Respond to Clicks on a Page

Lesson 42 of 81 2 min read By Deepak Paswan Updated Oct 4, 2026

HTML says what is on the page. JavaScript lets the page react. The basic pattern is: find an element, listen for an event, then change something.

index.html
HTML
<button id="toggle">Show opening hours</button>
<p id="hours" hidden>Open every day, 9:00 to 18:00.</p>

<script>
  const button = document.getElementById("toggle");
  const hours = document.getElementById("hours");

  button.addEventListener("click", function () {
    hours.hidden = !hours.hidden;
    button.textContent = hours.hidden ? "Show opening hours" : "Hide opening hours";
  });
</script>

What happens

  1. getElementById finds the button and the paragraph by their id values.
  2. addEventListener("click", ...) runs the function whenever the button is clicked.
  3. Inside the function the paragraph’s hidden property is flipped, and the button text is updated.

Why ids and classes matter

This is why id and class exist. JavaScript uses them to find the elements it should change.

lightbulb
Use a button for actions
Use a real button element for things that do something on the page, not a link or a div. Buttons work with the keyboard by default.

Exercise: a counter

Make a button that shows a number. Each click adds one to the number.

Show a possible solution
index.html
HTML
<button id="count">Clicked 0 times</button>
<script>
  let n = 0;
  const b = document.getElementById("count");
  b.addEventListener("click", function () {
    n++;
    b.textContent = "Clicked " + n + " times";
  });
</script>