JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 12: Events and InteractionLesson 56 of 150About 40 minutes

Lesson 56: Event listeners

01Opening question

A page sits still until someone clicks, types or scrolls. How does your code find out that it happened?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

addEventListener stores a function and the browser calls it every time the event happens. Here click() fires the event from code so you can see it in the console; in the preview you can click the button yourself.

const button = document.querySelector("#hello");
button.addEventListener("click", () => {
  console.log("Hello!");
});
button.click();
button.click();

03Objective and prerequisites

Learning objective: Attach event listeners with addEventListener, respond to clicks and key presses, and remove listeners you no longer need.

You need: Lesson 55: Updating styles, attributes and classes, Lesson 46: Global, function and block scope

Skills practised: Events, Event listeners.

04Explanation

An event is a signal that something happened: a click, a key press, text typed into a field, a page finishing loading.

element.addEventListener("click", handler) asks the browser to call handler every time that element is clicked. The function is called a listener or handler.

You pass the function itself, without calling it: addEventListener("click", save), not addEventListener("click", save()).

The same element can have many listeners, and the same function can listen on many elements. removeEventListener with the same function stops listening.

05Definitions

Event
A signal from the browser that something happened, such as a click or a key press.
Event listener
A function registered with addEventListener that runs when a given event happens on an element.
Event type
The name of an event, such as "click", "input" or "keydown".
removeEventListener
Stops a listener; it needs the same event type and the same function reference that was added.
once option
{ once: true } makes a listener remove itself after it runs one time.

Open the full glossary

06Visual learning object

Event listener laboratory. Attach, trigger and remove listeners on a live preview and watch which handlers run, in order.

Loading the interactive object…

Open the full Event listener laboratory page with its guided experiment.

07Examples

ex-056-01A click counter Browser page (sandboxed preview)

Each click runs the listener, which updates a variable and the page.

const button = document.querySelector("#add");
const output = document.querySelector("#count");
let count = 0;
button.addEventListener("click", () => {
  count++;
  output.textContent = count;
});
button.click();
button.click();
button.click();
console.log(output.textContent);
Sample input
None
Expected output
3

A button and a paragraph showing 3

Common mistake
Writing addEventListener("click", update()) which calls update once immediately and registers undefined.
Try this
Add a Reset button that sets the count back to 0.
Source
examples/ex-056-01-counter-button.js

ex-056-02Two listeners on one button Browser page (sandboxed preview)

Listeners run in the order they were added, and both run.

const save = document.querySelector("#save");
save.addEventListener("click", () => console.log("validate"));
save.addEventListener("click", () => console.log("store"));
save.onclick = () => console.log("property A");
save.onclick = () => console.log("property B");
save.click();
Sample input
None
Expected output
validate store property B
Common mistake
Using the onclick property in two places and losing the first handler.
Try this
Swap the order of the two addEventListener calls and predict the output.
Source
examples/ex-056-02-two-listeners.js

ex-056-03Removing a listener Browser page (sandboxed preview)

removeEventListener needs the same function, so give it a name.

const tip = document.querySelector("#tip");
function showTip() {
  console.log("Tip: press / to search");
}
tip.addEventListener("click", showTip);
tip.click();
tip.removeEventListener("click", showTip);
tip.click();
console.log("done");
Sample input
None
Expected output
Tip: press / to search done
Common mistake
Calling removeEventListener with a new arrow function, which never matches the one that was added.
Try this
Use { once: true } instead of removeEventListener.
Source
examples/ex-056-03-remove-listener.js

ex-056-04Responding to keys Browser page (sandboxed preview)

keydown listeners receive the key that was pressed.

const search = document.querySelector("#search");
search.addEventListener("keydown", (event) => {
  if (event.key === "Enter") console.log("Search for:", search.value);
  if (event.key === "Escape") {
    search.value = "";
    console.log("Cleared");
  }
});
search.value = "lamps";
search.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter" }));
search.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
console.log(JSON.stringify(search.value));
Sample input
None
Expected output
Search for: lamps Cleared ""
Common mistake
Comparing event.key with "enter"; key names are case-sensitive ("Enter").
Try this
Also handle the ArrowDown key.
Source
examples/ex-056-04-keyboard.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Pass the function, do not call it

Register a handler correctly.

let likes = 0;
function addLike() {
  likes++;
  document.querySelector("#likes").textContent = likes;
}
document.querySelector("#like").addEventListener("click", addLike());
document.querySelector("#like").click();
document.querySelector("#like").click();
console.log(likes);

Toggle a menu

Show and hide an element on click.

const button = document.querySelector("#menu-button");
const menu = document.querySelector("#menu");
// TODO: on click, toggle menu.hidden and set aria-expanded to "true" or "false"
button.click();
console.log(menu.hidden, button.getAttribute("aria-expanded"));

Dismiss once

Run a listener a single time.

// When #close is clicked: remove #banner and log "Banner closed".
// The handler must run only once, even if close is clicked again.

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: <button id="b">Go</button>
const b = document.getElementById("b");
function go() { console.log("go"); }
b.addEventListener("click", go);
b.addEventListener("click", go);
b.click();

How many times is go printed?

10Debugging investigation

Pausing the game does not stop the keys

Pressing Space should add a point until Pause is clicked. After pausing, Space still adds points.

let score = 0;
document.addEventListener("keydown", (e) => {
  if (e.key === " ") score++;
});
document.querySelector("#pause").addEventListener("click", () => {
  document.removeEventListener("keydown", (e) => {
    if (e.key === " ") score++;
  });
});
document.dispatchEvent(new KeyboardEvent("keydown", { key: " " }));
document.querySelector("#pause").click();
document.dispatchEvent(new KeyboardEvent("keydown", { key: " " }));
console.log("Score: " + score);

More cases in the Debugging Detective Laboratory

11Practical scenario

Keyboard shortcuts in a web app

An email app listens for keydown on the document. Pressing c opens a new message, / focuses search, and Escape closes dialogs. One listener checks event.key and calls the right function.

const shortcuts = { c: "compose", "/": "search", Escape: "close" };
for (const key of ["c", "/", "x"]) console.log(key, "->", shortcuts[key] ?? "ignored");

12Knowledge check

1. What does addEventListener do?

  • Runs a function immediately
  • Registers a function to run when an event happens
  • Creates a new button
  • Fires a click event

2. Why does nothing happen when the button is clicked?

button.addEventListener("click", save());
  • save() is called once and its result (undefined) is registered
  • click is the wrong event name
  • Buttons cannot have listeners
  • The function must be async

3. What is printed?

btn.onclick = () => console.log("A");
btn.onclick = () => console.log("B");
btn.click();
  • A then B
  • B only
  • A only
  • Nothing

4. Why does this removeEventListener call not work?

el.addEventListener("click", () => go());
el.removeEventListener("click", () => go());
  • The arrow function is a new function, not the one that was added
  • removeEventListener does not exist
  • It needs a third argument
  • click listeners cannot be removed

5. Which option makes a listener run at most once?

  • { single: true }
  • { once: true }
  • { capture: true }
  • { passive: true }

6. Which is better for a component that may be removed later?

  • Inline anonymous listeners everywhere
  • Listeners registered with an AbortController signal, aborted on teardown
  • onclick properties
  • Never removing listeners

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Pass the function, do not call it: Prints 2; The page shows 2
  • Toggle a menu: One click opens the menu; A second click closes it
  • Dismiss once: Logs once after two clicks; The banner is gone

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-12-events-and-interaction/lesson-056-event-listeners/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Events tell your code that something happened.
  • addEventListener registers a function; pass it without calling it.
  • Several listeners can run for one event, in registration order.
  • Remove listeners with the same function reference, { once: true } or an AbortController.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation event listeners
Context: I am learning event listeners in JavaScript.
Task: Explain addEventListener and removeEventListener with a small HTML page and buttons.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction event listeners drill
Context: I have practised event listeners.
Task: Give me six short listener programs that use click() and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging event listeners bug
Context: My click handler runs once when the page loads and never again.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation event listeners practice
Context: I finished the event listeners exercises.
Task: Create three exercises with buttons and keyboard events, each with exact expected output.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review event listeners review
Context: Here is my code that uses event listeners.
Task: Review my event listener code for listeners that can never be removed or that replace each other.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.