Thuta Learning
JavaScript
IntermediateProgrammingBeginner

DOM Events

JavaScriptLesson 2725 min

What you'll walk away with

  • Call addEventListener with a function reference instead of calling the function by accident
  • Explain event.target versus event.currentTarget and how events bubble
  • Use event delegation with closest() so elements added later are handled too
  • Control form submission with preventDefault() and remove listeners with AbortController or removeEventListener

Explain it simply

Explain it simply

An event is something that happens on the page: a button click, a key press, a form being sent, the page finishing loading. addEventListener() tells the browser "when this happens, call this function", like asking someone to open the door whenever the doorbell rings.

When the event happens, the browser calls your function with an event object describing it: which event, which element it happened on, which key was pressed. And the event then rises from the clicked element up through its parents, like a bubble, which is called bubbling.

Problem → Why → Solution

The problem: handlers that fire at once, and new items that ignore clicks

This todo-list code tries to attach a listener to every delete button. As soon as the page opens, every item is deleted at once, and clicking the buttons does nothing. Even after that is fixed, any item the user adds later has a delete button that ignores clicks.

todo-buggy.js
const buttons = document.querySelectorAll(".delete");

buttons.forEach((button) => {
  // Bug 1: removeItem(button) runs NOW and its return value is registered
  button.addEventListener("click", removeItem(button));
});

// Bug 2: buttons created later never received a listener
list.append(createTodoItem("Buy rice"));

Why does this happen?

Writing removeItem(button) with parentheses calls the function immediately and passes its result, undefined, to addEventListener. To have it called later you must pass a function reference such as () => removeItem(button). The second bug happens because listeners were attached once, only to buttons that existed at the time. One listener on the parent list that relies on bubbling, called event delegation, handles new items automatically.

Core concept: the journey of an event

element.addEventListener(type, handler, options) calls handler every time an event of that type ("click", "submit", "keydown", "input") happens. One element can have many listeners, and they run in the order they were added. element.onclick = fn holds only one handler and a second assignment wipes out the first, so prefer addEventListener.

text
A click on <button> inside <li> inside <ul>
-------------------------------------------
            document                 1. capture phase: travels DOWN
               |                         document -> ul -> li
              ul    <-- listener here    2. target phase: at the button
               |                         3. bubble phase: travels UP
              li                             button -> li -> ul -> document
               |
            button  <-- user clicks      target        = button (fixed)
                                         currentTarget = element whose
                                                         listener is running

When a click happens, the event travels down from document to the target element (capture phase), arrives at the target (target phase), then climbs back through the parents to document (bubble phase). Listeners run in the bubble phase by default; the { capture: true } option makes one run during capture instead. That is why a listener on a ul hears clicks from every button inside it. A few events, such as focus and blur, do not bubble (focusin and focusout do).

On the event object, event.target is the element where the event started, the innermost element that was clicked, while event.currentTarget is the element whose listener is running right now. event.preventDefault() cancels the browser's default action, such as reloading the page on form submit or following a link. event.stopPropagation() halts bubbling, which can silently break listeners on parents such as analytics or close-the-dropdown code, so use it rarely.

Depending on the event type, the event object carries extra details. For keyboard events, event.key names the key that was pressed, such as "Enter", "Escape" or "a", and for pointer events clientX and clientY give the position. On input fields, the input event fires on every single change, while change fires only when the user leaves the field (or picks a checkbox or select option). Choose input for features that react instantly, such as live search.

Mental model: events bubble up the tree
  1. User clicks the innermost element
  2. Event bubbles from target to parents
  3. Parent listener inspects event.target
  4. closest() finds which item was hit

One listener on a parent hears events from all its children, including ones added later; that is event delegation.

General pattern

javascript
element.addEventListener("eventType", (event) => {
  event.target;          // where the event started
  event.currentTarget;   // the element this listener is on
  event.preventDefault(); // cancel the browser's default action
}, { once: false, capture: false, signal: controller.signal });

parent.addEventListener("click", (event) => {
  const item = event.target.closest("[data-action]");
  if (item === null) return;   // click was not on an action element
});

You pass a function reference as the handler and the browser calls it with the event object. In the options, once: true runs the listener a single time and signal lets an AbortController remove it. The second shape is delegation: listen on a parent and use closest() to find the element you care about.

Example: a like button and a delegated todo list

This code builds its own buttons, so it runs in the console of a blank page. The like button gets an ordinary listener, while the todo list gets a single listener on the ul instead of one per Done button. To make the output predictable, the last lines simulate clicks with click(); clicking by hand gives the same result.

events-demo.js
// Paste into the console of a blank page: it builds the buttons it listens to.
const panel = document.createElement("div");
panel.innerHTML = `
  <button id="likeBtn">Like</button>
  <ul id="todos">
    <li><span>Buy rice</span> <button data-action="done">Done</button></li>
    <li><span>Call mum</span> <button data-action="done">Done</button></li>
  </ul>`;
document.body.append(panel);

let likes = 0;
const likeBtn = panel.querySelector("#likeBtn");
likeBtn.addEventListener("click", (event) => {
  likes += 1;
  console.log(`${event.type} on #${event.target.id}: ${likes} like(s)`);
});

// One listener on the parent handles every "Done" button (event delegation)
const todos = panel.querySelector("#todos");
todos.addEventListener("click", (event) => {
  const button = event.target.closest('[data-action="done"]');
  if (button === null) return;          // the click was not on a Done button
  const item = button.closest("li");
  item.classList.add("done");
  console.log(`Done: ${item.querySelector("span").textContent}`);
  console.log(`currentTarget is the list: ${event.currentTarget === todos}`);
});

// Simulate clicks so the output is predictable (real clicks behave the same)
likeBtn.click();
likeBtn.click();
todos.querySelectorAll("button")[1].click();

Code breakdown

  1. A direct listenerlikeBtn.addEventListener("click", (event) => {

    The arrow function is passed as a reference, so it runs on every click. likes lives outside the listener, so its value survives between clicks.

  2. One listener for many buttonstodos.addEventListener("click", (event) => {

    The Done buttons have no listeners of their own. A click on one bubbles up through its li to the ul, where this listener hears it.

  3. Find the real targetconst button = event.target.closest('[data-action="done"]');

    event.target is the innermost element, which could be a child such as an icon inside the button. closest() starts at the target and searches upward, so you get the button wherever inside it the user clicked.

  4. Ignore other clicksif (button === null) return; // the click was not on a Done button

    Clicking the span or empty space in the li makes closest() return null, so the listener just returns. Every delegated listener needs this guard.

  5. target versus currentTargetconsole.log(`currentTarget is the list: ${event.currentTarget === todos}`);

    event.target is the clicked button, while event.currentTarget is the ul the listener is attached to, so this prints true.

  6. Simulated clickstodos.querySelectorAll("button")[1].click();

    click() dispatches a click event that bubbles exactly like a real one, so the ul listener marks "Call mum" as done.

You should see
click on #likeBtn: 1 like(s)
click on #likeBtn: 2 like(s)
Done: Call mum
currentTarget is the list: true

Removing listeners

removeEventListener(type, handler) needs the exact function object that was given to addEventListener. If you wrote an inline arrow function, there is no reference left to remove, so store the function in a variable first. Simpler still, pass { signal: controller.signal } and call controller.abort(), which removes every listener tied to that signal in one go. { once: true } removes a listener automatically after its first run. Forgetting to remove listeners in short-lived UI such as modals and popups leads to memory leaks and handlers that run twice.

In real projects

Where this shows up in real projects

In UIs whose item count keeps changing, such as todo lists, table rows or comment threads, teams attach one listener to the container instead of one per row and route actions with attributes like data-action="complete" or data-action="delete". A thousand rows still means one listener, which saves memory, and re-rendering the rows never requires re-attaching anything.

Forms listen for the submit event, call preventDefault() to stop the page reload, and send the data with fetch(). Listening to the form's submit rather than the button's click also catches the user pressing Enter. For accessibility, build clickable things with <button> rather than a div: a <button> can be focused with the keyboard and fires a click event on Enter or Space by itself.

Common mistakes

Common mistakes

1. Calling the handler instead of passing it

addEventListener("click", save()) runs save once during setup and then does nothing on clicks. Write addEventListener("click", save), or () => save(id) when you need to pass an argument.

2. Trusting event.target directly in delegation

When a button contains a <span> or <svg> icon, event.target is that icon and event.target.dataset.action is undefined. Use event.target.closest("[data-action]") and check for null.

3. Trying to remove an inline arrow function

addEventListener("click", () => go()) followed by removeEventListener("click", () => go()) removes nothing, silently, because the two arrow functions are different objects. Keep the function in a variable or use an AbortController.

4. Placing preventDefault() after an early return

If a submit handler returns early on failed validation before reaching preventDefault(), the browser sends the form, the page reloads and even your console logs vanish. Put preventDefault() on the handler's first line.

Best practices

Best practices

  • Build clickable things with <button> and links with <a href>; keyboard and screen-reader support come for free.
  • For lists whose items come and go, delegate from the container instead of attaching a listener to every row.
  • Keep handlers for frequent events such as scroll and resize light, and debounce them when needed.

Mini challenge

Mini challenge: a task form that never reloads

Build a form with an input and an Add button, and add tasks to a list on its submit event. The page must not reload, whitespace-only input is ignored, and at the end the listener is removed with an AbortController. Your solution must create the elements it needs itself.

  • Listen to the form's submit event, not the button's click
  • Call event.preventDefault() as the handler's first line
  • trim() the text and print "Ignored an empty task" when it is empty
  • Build the li with createElement and textContent, then clear the input
  • Attach with a { signal } option and show that after abort() a submit adds nothing
task-form.js
// TODO: create a <form> with <input name="task"> and an Add <button>,
//       plus a <ul>, and append them to document.body

const controller = new AbortController();

function handleSubmit(event) {
  // TODO: stop the page reload first
  // TODO: read and trim form.elements.task.value; ignore empty text
  // TODO: append a new <li> (textContent), clear the input, log the total
}

// TODO: register handleSubmit for "submit" with { signal: controller.signal }
// TODO: submit "Water the plants" and "   " with form.requestSubmit()
// TODO: abort, dispatch one more submit event, then log the list size

Expected: The console shows the following and the page never reloads: Added: Water the plants (total 1) Ignored an empty task Items in the list: 1

Show hint

form.requestSubmit() fires a submit event just like the user pressing Enter. Call preventDefault() before any early return so the empty case does not reload either. After abort(), use dispatchEvent(new Event("submit", { cancelable: true })) instead of requestSubmit(); a synthetic submit event never actually sends the form.

Show solution
task-form.js
// Builds its own form, so it works on any blank page.
const form = document.createElement("form");
form.innerHTML = '<input name="task" aria-label="New task"><button>Add</button>';
const list = document.createElement("ul");
document.body.append(form, list);

const controller = new AbortController();

form.addEventListener(
  "submit",
  (event) => {
    event.preventDefault(); // stop the browser from reloading the page
    const input = form.elements.task;
    const text = input.value.trim();
    if (text === "") {
      console.log("Ignored an empty task");
      return;
    }
    const li = document.createElement("li");
    li.textContent = text;
    list.append(li);
    input.value = "";
    console.log(`Added: ${text} (total ${list.children.length})`);
  },
  { signal: controller.signal },
);

form.elements.task.value = "Water the plants";
form.requestSubmit(); // same as pressing Enter or clicking Add
form.elements.task.value = "   ";
form.requestSubmit();

controller.abort(); // removes the listener
form.elements.task.value = "Too late";
form.dispatchEvent(new Event("submit", { cancelable: true })); // no listener now
console.log(`Items in the list: ${list.children.length}`);

Quick quiz 1 / 3

What happens with btn.addEventListener("click", sayHi()); when sayHi returns nothing?

Quick quiz 2 / 3

A click listener sits on a ul. The user clicks a <span> icon inside a button inside an li. Inside the listener, what is event.currentTarget?

Quick quiz 3 / 3

After btn.addEventListener("click", () => log());, what does btn.removeEventListener("click", () => log()); do?

What to remember

  • Pass addEventListener a function reference: save or () => save(id), never save().
  • Events travel capture, target, then bubble, and listeners run in the bubble phase by default.
  • event.target is where the event started and event.currentTarget is where the listener sits; in delegation use closest() and check for null.
  • Use preventDefault() to cancel default actions, stopPropagation() rarely, and AbortController or once to remove listeners.

MDN — Document Object Model (DOM) — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

DOM Events | Thuta Learning