Events & Listeners in JavaScript
Events connect user and system occurrences to code: addEventListener(type, handler, options) subscribes (multiple handlers per event, unlike on* properties which allow one), removeEventListener unsubscribes (same reference required — anonymous functions can't unsubscribe), and the Event object carries details (target, key, coordinates) plus control (preventDefault, stopPropagation).
{ once: true } auto-removes one-shot listeners; { passive: true } promises no preventDefault for scroll performance; { signal } ties lifetime to an AbortController. Cleanup on teardown prevents leaks — listeners outlive removed elements when referenced.
Subscribe with addEventListener
btn.addEventListener("click", onClick) — stackable handlers, unlike btn.onclick assignment.
Read the event object
e.target (origin), e.key (which key), e.clientX/Y (position) — details ride along automatically.
Control defaults and flow
e.preventDefault() stops native behavior (form submit, link nav); e.stopPropagation() halts bubbling.
Unsubscribe to clean
removeEventListener with the same function reference — named handlers clean up, anonymous ones can't.
let count = 0;function onClick(e) { count++; console.log("clicked", count, e.type);}document.querySelector("#btn").addEventListener("click", onClick, { once: false });Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.