← Web basics: HTML, CSS and JavaScript

Click events

Run code when someone clicks, with addEventListener.

Start this lesson

So far our scripts ran once, when the page loaded. Events let code run later, when something happens: a click, a key press, typing in a box. element.addEventListener("click", handler) says "whenever this element is clicked, run handler". The handler is a function. You pass the function itself, without calling it, so the browser can call it at the right moment, as many times as needed.

<button id="hello">Say hello</button>
<p id="out"></p>

<script>
  const button = document.querySelector("#hello");
  const out = document.querySelector("#out");

  function sayHello() {
    out.textContent = "Hello there!";
  }

  button.addEventListener("click", sayHello);
</script>

Nothing happens at load time except setting up the listener. Every click on the button runs sayHello. Note: sayHello without parentheses.

A classic bug is writing addEventListener("click", sayHello()) with parentheses. That calls sayHello immediately, once, and hands its result (undefined) to the listener instead of the function.

You can also write the function right inside: button.addEventListener("click", () => { out.textContent = "Hi"; });