freecoding.school100% FREE · NO SIGNUP
The DOM ForestISSUE #11 of 21

events · addEventListener · removeEventListener

NodetteVSThe Event Bubbler
Nodette saysaddEventListener attaches a handler to an event; removeEventListener detaches it.

el.addEventListener("click", fn) is the modern way to react to events — you can attach many handlers to one element, unlike the old onclick. Remove with removeEventListener("click", fn) (the same function reference is required). Options like { once: true } and { passive: true } tune behavior.

Power-ups you unlock

The Event Bubbler attacks — common mistakes

Boss battleAdd a click handler, then a once:true handler that fires a single time.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;padding:20px"><button id="b">click</button><p id="o"></p>
<script>let n=0;const o=document.getElementById('o');
document.getElementById('b').addEventListener('click',()=>o.textContent='clicks: '+(++n));</script></body></html>
▶ Open the interactive comic issue
‹ Forms · Accessing ValuesEvent Object · Target · CurrentTarget ›