Level: Intermediate | Player: 18_DOM_Manipulation
Learning Objectives
- Change the event handler to
addEventListener - Read target, type, etc. from the event object.
- Distinguish between
preventDefaultandstopPropagation. - Reduce the number of handlers by utilizing event delegation.
- Know the concept of Capture/Bubble steps.
1. addEventListener
btn.addEventListener("click", handler);
btn.removeEventListener("click", handler);
You must pass the same function reference to remove it. Anonymous functions cannot be removed.
2. Event object
The callback receives a Event object.
event.target: Element where the event actually occurredevent.currentTarget: Element with listener attachedevent.type: "click", "input", etc.event.key,event.code: Keyboard event
3. preventDefault / stopPropagation
preventDefault(): Blocks basic operations (form submission, link movement, etc.).stopPropagation(): Prevent events from propagating to parents.
4. Event delegation
When there are many children, do not register them individually, but process them from one parent.
list.addEventListener("click", (e) => {
const li = e.target.closest("li");
if (!li) return;
console.log("Items clicked:", li.textContent);
});
5. Capture and Bubbles
Events propagate from window → target → parent (capture → bubble). The default is called in the bubble phase, and you can also register the capture phase as addEventListener(type, fn, { capture: true }).
Core example
| file | Contents covered |
|---|---|
| index.html | Example HTML |
| 01_addeventlistener.js | Event Register/Cancel |
| 02_event_object.js | Event object properties |
| 03_prevent_default.js | Use preventDefault |
| 04_delegation.js | Event Delegation |
⚠️ Common Mistakes
- Problem that only one handler can be registered at a time with
onclick = fn. - Register an anonymous function and then attempt to remove it.
- Confusion between
event.targetandevent.currentTarget. - When you submit the form,
preventDefaultis forgotten and the page is refreshed. - There are no events for dynamically added children, so I cannot see a situation where delegation is necessary.
❓ Frequently Asked Questions (FAQ)
Q1. What is the once option? A. { once: true } is executed only once and is automatically released.
Q2. What about passive listeners? A. For scroll performance, if you register as { passive: true }, the preventDefault call will be ignored.
Q3. Is it always good to prevent event propagation? A. Only when absolutely necessary, as it may break other handlers.