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.
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.
Prefer addEventListener over onclick = ... properties: properties hold only one handler, so a second assignment silently replaces the first.
Removing a listener needs the same function reference. An inline arrow function cannot be removed later, so keep a named reference when you plan to remove it, or pass { once: true }.
An AbortController signal ({ signal }) removes every listener registered with it in one abort() call, which is the cleanest teardown for components.
element.click() and dispatchEvent(new Event("input")) fire events from code. Tests use them to simulate users; listeners run synchronously during dispatch.
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.
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.
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.
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
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.
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 explanationevent 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 predictionevent 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.
Debuggingevent 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 generationevent 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 reviewevent 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.