Skip to content
Kuza Ndoto Academy

Events

Beginner → IntermediateChapter 4 · Page 20 of 325 min readUpdated 15 Nov 2026

An event is a signal that something happened: a click, a key press, text typed into a box, a page finishing loading. You tell the browser "when this happens on that element, run this function" with addEventListener. Events are how a page responds to the person using it.

addEventListener

Select an element, then call addEventListener(type, handler). The handler is a function the browser calls each time the event happens. It receives an event object full of details.

<button id="buy">Buy airtime</button>
const buy = document.querySelector("#buy");

buy.addEventListener("click", (event) => {
  console.log("Clicked!", event.type, event.target.id);
});
Clicked! click buy

The output appears each time the button is clicked, not when the script runs. You pass the function itself; the browser decides when to call it. This is a callback, an idea explored further in Callbacks & the Event Loop.

Common mistake

buy.addEventListener("click", sayHello()) calls sayHello immediately and passes its return value (usually undefined) as the handler, so clicks do nothing. Pass the function without brackets: addEventListener("click", sayHello), or wrap it: () => sayHello("Amina").

Common event types

EventFires whenUseful event properties
clickAn element is clicked or tapped (or activated with Enter/Space on a button)target
inputThe value of a text box, slider or select changes, on every keystroketarget.value
changeA value is committed (checkbox ticked, select chosen, text box loses focus)target.value, target.checked
keydown / keyupA key is pressed / releasedkey, shiftKey, ctrlKey
submitA form is submittedsee Handling Forms
focus / blurAn element gains / loses focustarget
DOMContentLoadedThe HTML has been parsed into the DOM (listen on document)

Input and keyboard events

The input event lets you react while someone types, for example to show a live character count. Keyboard events tell you which key was pressed through event.key, a readable string such as "a", "Enter" or "ArrowLeft".

document.addEventListener("keydown", (event) => {
  console.log(event.key);
});

Pressing the A key, then Enter, then the left arrow logs:

a Enter ArrowLeft

Old tutorials use event.keyCode (numbers like 13). It is deprecated; use event.key.

Bubbling: events travel upwards

When you click an element, the event doesn't stop there. After handlers on the target run, the event bubbles up through each ancestor (parent, grandparent and so on) up to document, triggering their listeners too.

<div id="card">
  <button id="pay">Pay</button>
</div>
document.querySelector("#pay").addEventListener("click", () => console.log("button"));
document.querySelector("#card").addEventListener("click", (event) => {
  console.log("card: target =", event.target.id, "/ currentTarget =", event.currentTarget.id);
});
document.addEventListener("click", () => console.log("document"));

Clicking the button logs:

button card: target = pay / currentTarget = card document

Notice the two properties: event.target is the element that was actually clicked, while event.currentTarget is the element whose listener is running now. If you ever need to stop the journey upwards, call event.stopPropagation(), but use it rarely, because other code may rely on bubbling.

Event delegation

Bubbling enables a powerful pattern. Instead of attaching a listener to every li in a list, attach one listener to the parent ul and work out which item was clicked with event.target.closest("li"). This uses less memory, and it also works for items you add later.

const tasks = document.querySelector("#tasks");

tasks.addEventListener("click", (event) => {
  const item = event.target.closest("li");
  if (!item) return;                 // the click was on the ul itself, not an item
  item.classList.toggle("done");
});
document body ul#tasks (one listener) li: Buy unga li: Revise JS (clicked) li: Call mum document body ul#tasks li (target) click starts here listener runs keeps going ends here
Figure 1. A click on an li bubbles up through its ancestors. A single listener on ul#tasks catches clicks on every item, and event.target says which one.

Removing listeners and running once

To remove a listener you must pass the same function you added, so give it a name. If a handler should only ever run once, pass the option { once: true }.

function showReceipt() {
  console.log("Receipt shown");
}
buy.addEventListener("click", showReceipt);
buy.removeEventListener("click", showReceipt);    // works: same function

buy.addEventListener("click", () => console.log("Welcome bonus!"), { once: true });
Tip

You may see button.onclick = function () {...} or onclick="..." in HTML. They work, but an element can only hold one onclick at a time, so a second assignment silently replaces the first. addEventListener lets many handlers coexist and keeps JavaScript out of your HTML.

Try it: live counter and delegated list

Type in the box to see the input event, press Enter to add a task (a keydown event), and click any task, even new ones, to toggle it. Only one click listener exists, on the ul.

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    li { cursor: pointer; padding: 4px; }
    .done { text-decoration: line-through; color: gray; }
  </style>
</head>
<body>
  <input id="task" maxlength="50" placeholder="Type a task, press Enter">
  <p id="chars">0 / 50</p>
  <ul id="tasks">
    <li>Buy unga</li>
    <li>Revise JavaScript</li>
  </ul>
  <p id="log">Click a task to mark it done.</p>

  <script>
    const input = document.querySelector("#task");
    const chars = document.querySelector("#chars");
    const tasks = document.querySelector("#tasks");
    const log = document.querySelector("#log");

    input.addEventListener("input", (event) => {
      chars.textContent = `${event.target.value.length} / 50`;
    });

    input.addEventListener("keydown", (event) => {
      if (event.key === "Enter" && input.value.trim() !== "") {
        const li = document.createElement("li");
        li.textContent = input.value.trim();
        tasks.append(li);
        input.value = "";
        chars.textContent = "0 / 50";
      }
    });

    tasks.addEventListener("click", (event) => {
      const item = event.target.closest("li");
      if (!item) return;
      item.classList.toggle("done");
      log.textContent = `You clicked: ${item.textContent}`;
    });
  </script>
</body>
</html>

Key points

  • element.addEventListener(type, handler) runs the handler every time the event fires; pass the function, don't call it.
  • The event object tells you type, target, key and more.
  • Events bubble from the target up to document; target is where it started, currentTarget is where the listener sits.
  • Event delegation puts one listener on a parent and uses event.target.closest() to find the item, including items added later.
Up next · The DOM & EventsHandling FormsRead form values, validate input and prevent default.
→

Tip: use the ← and → keys to move between pages.