πŸ–±οΈ
CodingπŸŽ“ Ages 14-18Intermediate 13 min read

JavaScript Events and Clicks

A practical teen tutorial on JavaScript events: listen for clicks and other user actions with addEventListener, write event handler functions, read the event object, and make pages interactive, with runnable code and a quiz.

Key takeaways

  • An event is something that happens on the page, like a click or a key press
  • addEventListener connects an element, an event name and a handler function
  • The handler function runs every time that event happens
  • Common events include click, input, keydown, mouseover and submit
  • The event object passed to the handler holds details about what happened

Making pages react

So far a web page mostly sits there. Events are what make it come alive. An event is something that happens in the browser β€” a button click, a key press, the mouse moving, a form being submitted. With JavaScript you can listen for these events and run code in response. That's the heart of interactivity: click this, and something happens.

This lesson builds on selecting elements from the page, so it helps to have read JavaScript and the DOM first. Here we focus on the most important interaction of all β€” the click β€” and the general system that powers every event.

The three pieces of an event

To respond to an event you connect three things:

  1. An element β€” what the user interacts with (a button, a box, the whole document).
  2. An event name β€” what to listen for ("click", "input", "keydown"...).
  3. A handler function β€” the code to run when it happens.

The method that ties them together is addEventListener:

element.addEventListener("click", handlerFunction);

Read it as: "On element, when a click happens, run handlerFunction."

Your first click handler

Suppose this is in your HTML:

<button id="myButton">Click me</button>
<p id="output"></p>

In JavaScript you grab the button and listen for clicks:

const button = document.getElementById("myButton");
const output = document.getElementById("output");

button.addEventListener("click", function () {
  output.textContent = "You clicked the button!";
});

Now every time the button is clicked, the function runs and updates the paragraph. Click it three times and it runs three times β€” the listener stays active.

Named functions vs inline functions

You can pass an existing function by name instead of writing it inline:

function sayHi() {
  console.log("Hi!");
}

button.addEventListener("click", sayHi);   // no parentheses!

This is the single most common beginner mistake, so look closely: you write sayHi without parentheses. With parentheses β€” sayHi() β€” the function would run immediately when the page loads, and only its return value would be handed to addEventListener. Passing the name lets the browser call it later, at click time.

The event object

When the browser calls your handler, it passes in an event object packed with details. Give your function a parameter (commonly named event or e) to receive it:

button.addEventListener("click", function (event) {
  console.log(event.type);     // "click"
  console.log(event.target);   // the button element that was clicked
});

Two useful properties:

  • event.type β€” the name of the event, like "click".
  • event.target β€” the exact element the event happened on. This is handy when one handler covers several elements.

For keyboard events, event.key tells you which key was pressed.

Other useful events

click is just one of many. The pattern is always the same β€” only the event name changes:

EventFires when...
clickan element is clicked
inputthe value of a text box changes as you type
keydowna key is pressed down
mouseoverthe pointer moves onto an element
submita form is submitted
changea select or checkbox changes

For example, reacting live to typing:

const nameBox = document.getElementById("nameBox");
const greeting = document.getElementById("greeting");

nameBox.addEventListener("input", function (event) {
  greeting.textContent = "Hello, " + event.target.value + "!";
});

As the user types, input fires on every keystroke and event.target.value holds the current text.

A complete worked example

Let's build a small interactive page: a button that counts clicks, and a live greeting that updates as you type. Save it as an .html file and open it in a browser.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Events Demo</title>
  <style>
    body { font-family: sans-serif; max-width: 420px; margin: 30px auto; }
    button { padding: 10px 16px; font-size: 16px; cursor: pointer; }
    input { padding: 8px; font-size: 16px; width: 100%; box-sizing: border-box; }
    .count { font-size: 24px; font-weight: bold; }
  </style>
</head>
<body>
  <h1>Try the events</h1>

  <p>Clicks: <span id="count" class="count">0</span></p>
  <button id="clicker">Click me</button>

  <p style="margin-top:24px;">Type your name:</p>
  <input id="nameBox" type="text" placeholder="Your name">
  <p id="greeting"></p>

  <script>
    // --- Click counter ---
    const clicker = document.getElementById("clicker");
    const countSpan = document.getElementById("count");
    let clicks = 0;

    clicker.addEventListener("click", function () {
      clicks = clicks + 1;          // update the variable
      countSpan.textContent = clicks; // show it on the page
    });

    // --- Live greeting ---
    const nameBox = document.getElementById("nameBox");
    const greeting = document.getElementById("greeting");

    nameBox.addEventListener("input", function (event) {
      const name = event.target.value;
      if (name === "") {
        greeting.textContent = "";
      } else {
        greeting.textContent = "Hello, " + name + "! πŸ‘‹";
      }
    });
  </script>
</body>
</html>

How it works:

  • The click listener keeps a clicks variable. Each click adds 1 and writes the new number into the <span>, so the page updates instantly.
  • The input listener reads event.target.value (whatever is currently in the box) every time you type, and rebuilds the greeting. If the box is empty it clears the message.

Notice the <script> is at the bottom of the <body>, so the elements exist before the JavaScript tries to find them.

Try it yourself

  1. Reset button. Add a second button that sets clicks back to 0 and updates the display.
  2. Change colour on click. In the click handler, set document.body.style.backgroundColor to a different colour each time.
  3. React to a key. Add a keydown listener on the nameBox that logs event.key, and notice it prints the exact key you pressed.

Challenge: Build a simple "like" button. Start a counter at 0, and each click increases it and updates a heart count next to the button. Then add a "dislike" button that decreases the count, but never lets it go below 0 (use an if). For an extra touch, change the button's text once the count passes 10. To level up afterwards, combine events with arrays in Building a To-Do List App.

Quick quiz

Test yourself and earn XP

What is an event in JavaScript?

Which method attaches a function to an event?

When does the handler function run?

Which event fires when a user types in a text box?

What does event.target refer to?

FAQ

Both work, but addEventListener is preferred. You can attach many listeners to the same element with it, and it keeps your JavaScript separate from your HTML. The onclick attribute mixes behaviour into your markup and can only hold one handler.

In addEventListener('click', greet) you pass the function name with NO parentheses, so the browser calls it later when the click happens. If you write greet() with parentheses, it runs immediately and passes the result instead, which is a common bug.