JavaScript Events
Published by Brayan K
Learn how to make your web pages come alive by responding to user interactions like clicks, key presses, and form submissions.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Register the response, then trigger the event
An event listener connects an event type, an event target and a callback. Registering the callback does not call it. The browser calls it when the event reaches that target. Callbacks & Callback Hell owns passing functions; DOM Manipulation owns creating and selecting the elements used here.
const app = document.getElementById("app");
app.innerHTML = '<button type="button">Add one</button><p role="status">Count: 0</p>';
const button = app.querySelector("button");
const status = app.querySelector("p");
let count = 0;
function increment() {
count++;
status.textContent = "Count: " + count;
}
button.addEventListener("click", increment);
console.log(count);
button.click();
button.click();
console.log(count, status.textContent);
// ✅ Expected output:
// 0
// 2 Count: 2The two click calls make the result repeatable; the rendered button also responds when you activate it yourself. A click event is not limited to a mouse: native buttons support keyboard activation too. Prefer a button over adding a click handler to an otherwise non-interactive div. The examples here create their own markup and run in Web page mode.
const button = document.createElement("button");
let count = 0;
function increment() { count++; }
button.addEventListener("click", increment());
console.log("after registration", count);
button.click();
console.log("after click", count);
// ✅ Expected output:
// after registration 1
// after click 1increment() ran immediately and returned undefined, so no callback was installed. This mistake need not throw. A function reference, increment, is the intended second argument. A string containing code is not a valid listener either.
const button = document.createElement("button");
button.addEventListener("click", "console.log('clicked')");
// ✅ Expected error:
// TypeError: Failed to execute 'addEventListener' on 'EventTarget': parameter 2 is not of type 'Object'.Listener identity controls duplicates and cleanup
The same target, event type, callback identity and capture setting describe one registration. Repeating that registration does not duplicate it. Creating another arrow function creates another callback, even if the source text looks identical. Keep a function reference when you will need to remove it.
const button = document.createElement("button");
function named() { console.log("named"); }
button.addEventListener("click", named);
button.addEventListener("click", named);
button.addEventListener("click", () => console.log("arrow"));
button.addEventListener("click", () => console.log("arrow"));
button.click();
// ✅ Expected output:
// named
// arrow
// arrowconst button = document.createElement("button");
let count = 0;
const increment = () => { count++; };
button.addEventListener("click", increment);
button.removeEventListener("click", () => { count++; });
button.click();
console.log(count);
button.removeEventListener("click", increment);
button.click();
console.log(count);
// ✅ Expected output:
// 1
// 1once removes a listener after its first invocation. An AbortSignal can manage a group of registrations: aborting its controller removes them. Use a new controller for a new lifetime; an already-aborted signal does not become active again. The signal’s use with network requests belongs to AbortController & Cancelling Async Work.
const button = document.createElement("button");
let count = 0;
button.addEventListener("click", () => { count++; }, { once: true });
button.click();
button.click();
console.log(count);
// ✅ Expected output:
// 1const a = document.createElement("button");
const b = document.createElement("button");
const controller = new AbortController();
let count = 0;
const increment = () => { count++; };
a.addEventListener("click", increment, { signal: controller.signal });
b.addEventListener("click", increment, { signal: controller.signal });
a.click();
b.click();
controller.abort();
a.click();
b.click();
console.log(count, controller.signal.aborted);
// ✅ Expected output:
// 2 trueWhere an event started and where it is being handled
For this ordinary DOM tree, target identifies the element where the event started; currentTarget identifies the object whose listener is running. Clicking a span inside a button can therefore make the span the target while the button is the currentTarget. Shadow DOM retargeting is a separate topic in Web Components & Custom Elements.
const button = document.createElement("button");
button.innerHTML = "<span>Add</span>";
button.addEventListener("click", event => {
console.log(event.target.tagName, event.currentTarget.tagName);
});
button.querySelector("span").click();
// ✅ Expected output:
// SPAN BUTTONA capturing listener runs on the way down toward the target. A bubbling listener on an ancestor runs on the way back up for an event that bubbles. Many events bubble, including click; not all event types do. Capture defaults to false, and removeEventListener must match the capture setting used when registering.
const parent = document.createElement("section");
const button = document.createElement("button");
parent.append(button);
parent.addEventListener("click", () => console.log("parent capture"), { capture: true });
button.addEventListener("click", () => console.log("button"));
parent.addEventListener("click", () => console.log("parent bubble"));
button.click();
// ✅ Expected output:
// parent capture
// button
// parent bubblestopPropagation stops the event progressing farther along that path. It does not remove other listeners already registered on the same target. stopImmediatePropagation also stops later listeners on that same target. Use either deliberately: stopping an event can prevent other parts of a page from observing it.
const parent = document.createElement("div");
const button = document.createElement("button");
parent.append(button);
button.addEventListener("click", event => {
console.log("first");
event.stopPropagation();
});
button.addEventListener("click", () => console.log("second"));
parent.addEventListener("click", () => console.log("parent"));
button.click();
// ✅ Expected output:
// first
// secondconst button = document.createElement("button");
button.addEventListener("click", event => {
console.log("first");
event.stopImmediatePropagation();
});
button.addEventListener("click", () => console.log("second"));
button.click();
// ✅ Expected output:
// firstCancel an action without confusing it with propagation
preventDefault requests cancellation of a cancelable event’s default action. It does not stop propagation. A non-cancelable event cannot be cancelled, and a passive listener cannot cancel an event either. The following synthetic event has no browser action attached; its flags let us inspect cancellation without navigating or submitting anything.
const parent = document.createElement("div");
const child = document.createElement("button");
parent.append(child);
child.addEventListener("save", event => event.preventDefault());
parent.addEventListener("save", event => {
console.log("parent saw cancellation", event.defaultPrevented);
});
const event = new Event("save", { bubbles: true, cancelable: true });
console.log("dispatch returned", child.dispatchEvent(event));
console.log(event.defaultPrevented);
const fixed = new Event("save");
child.dispatchEvent(fixed);
console.log(fixed.defaultPrevented);
// ✅ Expected output:
// parent saw cancellation true
// dispatch returned false
// true
// falseReturning false from an addEventListener callback does not cancel an event. Call preventDefault explicitly when cancellation is part of the intended behaviour. This differs from some older inline-handler conventions.
const target = document.createElement("button");
target.addEventListener("save", () => false);
const event = new Event("save", { cancelable: true });
console.log(target.dispatchEvent(event));
console.log(event.defaultPrevented);
// ✅ Expected output:
// true
// falseValue changes, key presses and submission are different events
input describes a user-driven value change, not every key press. Pasting can change text without typing individual characters; an arrow key can move the caret without changing the value. Assigning input.value in JavaScript does not fire input automatically. Use keydown for a key-specific interaction, and input for reacting to edited text.
const input = document.createElement("input");
input.setAttribute("aria-label", "Draft title");
document.getElementById("app").append(input);
let changes = 0;
input.addEventListener("input", () => {
changes++;
console.log("observed", input.value);
});
input.value = "Notes";
console.log("after assignment", changes);
input.dispatchEvent(new Event("input", { bubbles: true }));
console.log("after dispatch", changes);
// ✅ Expected output:
// after assignment 0
// observed Notes
// after dispatch 1The synthetic dispatch above exercises our listener; it does not type text or reproduce every detail of a trusted user interaction. change is also control-dependent: a text field commonly reports a committed edit when focus leaves, while a checkbox can report its change immediately. Do not assume one timing rule for every control.
Handle submit on the form when the action is form submission. A submit-button click is only one way to request it. requestSubmit runs validation and, for a valid form, dispatches submit; the older form.submit method bypasses those steps. Cancel submission here because this example updates an on-page message rather than sending data. A normal form that should navigate does not need automatic cancellation.
const form = document.createElement("form");
form.innerHTML = '<label>Name <input name="name" required></label><button type="submit">Save</button><p role="status"></p>';
document.getElementById("app").append(form);
const input = form.elements.namedItem("name");
const status = form.querySelector("p");
let submissions = 0;
form.addEventListener("submit", event => {
event.preventDefault();
submissions++;
status.textContent = "Saved " + input.value;
});
form.requestSubmit();
console.log("empty", submissions);
input.value = "Ada";
form.requestSubmit();
console.log("valid", submissions, status.textContent);
// ✅ Expected output:
// empty 0
// valid 1 Saved AdaOne parent can handle buttons added later
Event delegation registers a listener on a stable ancestor and examines events that bubble to it. Start from target, find the nearest matching button with closest, and check that it belongs to the intended container. Checking only target.tagName would miss a click on a nested label. Delegation works for the bubbling click event used here; it is not a replacement for understanding which events reach the ancestor.
const list = document.createElement("ul");
document.getElementById("app").append(list);
list.addEventListener("click", event => {
if (!(event.target instanceof Element)) return;
const button = event.target.closest("button[data-action]");
if (button === null || !list.contains(button)) return;
console.log(button.dataset.action, button.textContent);
});
const item = document.createElement("li");
item.innerHTML = '<button type="button" data-action="remove"><span>Remove A</span></button>';
list.append(item);
item.querySelector("span").click();
list.click();
// ✅ Expected output:
// remove Remove AGuided exercise: register, cancel and observe
Complete the three blanks to handle a cancelable event and inspect its final state. The callback receives the event object; the event name is supplied by the registration. All hints are literal substitutions.
const button = document.createElement("button");
button.___("save", event => { // 👉 replace ___ with addEventListener
event.___(); // 👉 replace ___ with preventDefault
});
const event = new Event("save", { cancelable: true });
button.dispatchEvent(event);
console.log(event.___); // 👉 replace ___ with defaultPrevented
// ✅ Expected output:
// trueIndependent brief: a removable task list with cleanup
Write mountTaskList(app, labels). Render a ul and a status paragraph. Each string label needs an li with a native Remove button containing a span. Register one delegated click listener on the ul. A click inside a remove button should remove that row and update the remaining count; a click on the list background should do nothing.
Return a dispose function that removes the listener. Check a nested-span click, an ignored background click, and a click after disposal. Keep labels as plain text, and use type="button" so these controls do not become submit buttons if the list later appears inside a form. This exercise deliberately has no server or persistent storage.
function mountTaskList(app, labels) {
const list = document.createElement("ul");
const status = document.createElement("p");
status.setAttribute("role", "status");
function renderCount() {
status.textContent = "Remaining: " + list.children.length;
}
for (const label of labels) {
const item = document.createElement("li");
const button = document.createElement("button");
const span = document.createElement("span");
button.type = "button";
button.dataset.action = "remove";
span.textContent = "Remove " + label;
button.append(span);
item.append(button);
list.append(item);
}
app.replaceChildren(list, status);
renderCount();
function removeTask(event) {
if (!(event.target instanceof Element)) return;
const button = event.target.closest('button[data-action="remove"]');
if (button === null || !list.contains(button)) return;
const item = button.closest("li");
if (item === null || item.parentElement !== list) return;
item.remove();
renderCount();
}
list.addEventListener("click", removeTask);
return () => list.removeEventListener("click", removeTask);
}
const app = document.getElementById("app");
const dispose = mountTaskList(app, ["Read", "Practise", "<Review>"]);
const list = app.querySelector("ul");
const status = app.querySelector("p");
console.log(status.textContent);
list.querySelector("span").click();
console.log(status.textContent);
list.click();
console.log(list.children.length);
dispose();
list.querySelector("button").click();
console.log(status.textContent);
console.log(list.lastElementChild.textContent);
const empty = document.createElement("section");
const disposeEmpty = mountTaskList(empty, []);
console.log(empty.querySelector("p").textContent);
disposeEmpty();
// ✅ Expected output:
// Remaining: 3
// Remaining: 2
// 2
// Remaining: 2
// Remove <Review>
// Remaining: 0
Practice quiz
What does this complete program print? const button = document.createElement("button"); let count = 0; function run() { count++; } button.addEventListener("click", run); console.log(count); button.click(); console.log(count);
- 0 1
- 1 2
- 0 0
- 1 1
Answer: 0 1. Registration stores the callback; the click invokes it.
What does this complete program print? const button = document.createElement("button"); let count = 0; const run = () => { count++; }; button.addEventListener("click", run); button.addEventListener("click", run); button.click(); console.log(count);
- 0
- 1
- 2
- 3
Answer: 1. Repeating the same registration with the same callback and capture setting does not add another listener.
What does this complete program print? const button = document.createElement("button"); button.innerHTML = "<span>Go</span>"; button.addEventListener("click", event => { console.log(event.target.tagName, event.currentTarget.tagName); }); button.querySelector("span").click();
- BUTTON BUTTON
- SPAN SPAN
- SPAN BUTTON
- BUTTON SPAN
Answer: SPAN BUTTON. The span is the target, while this listener is registered on the button.
What does this complete program print? const button = document.createElement("button"); let count = 0; button.addEventListener("click", () => { count++; }, { once: true }); button.click(); button.click(); console.log(count);
- 0
- 2
- undefined
- 1
Answer: 1. The once listener is removed after its first invocation.
What does this complete program print? const button = document.createElement("button"); button.addEventListener("save", event => event.preventDefault()); const event = new Event("save"); button.dispatchEvent(event); console.log(event.cancelable, event.defaultPrevented);
- false false
- true true
- false true
- true false
Answer: false false. The default Event constructor options do not make the event cancelable.
What does this complete program print? const input = document.createElement("input"); let count = 0; input.addEventListener("input", () => { count++; }); input.value = "Ada"; console.log(count, input.value);
- 1 Ada
- 0 Ada
- 0 undefined
- 1 undefined
Answer: 0 Ada. Assigning value does not dispatch input automatically.
What does this complete program print? const button = document.createElement("button"); let count = 0; const run = () => { count++; }; button.addEventListener("click", run, true); button.removeEventListener("click", run, false); button.click(); console.log(count);
- 0
- 2
- 1
- false
Answer: 1. Removal must match the capture flag; false does not remove the true registration.
What does this complete program print? const button = document.createElement("button"); button.addEventListener("save", () => false); const event = new Event("save", { cancelable: true }); console.log(button.dispatchEvent(event), event.defaultPrevented);
- false true
- true true
- false false
- true false
Answer: true false. The callback return value is ignored. Without preventDefault, dispatch succeeds without cancellation.
Continue this course
- Previous: DOM Manipulation
- Next: Arrays and Objects — Store lists and structured data, and loop through them efficiently
- Quick reference: JavaScript cheat sheet › DOM
- From the blog: Understanding the DOM in JavaScript · Understanding JavaScript Closures · How to Learn to Code Fast (Without Burning Out)