Learn JavaScript
❯ browser_dom.events

Events & Listeners in JavaScript

$concept

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.

$how it works
1

Subscribe with addEventListener

btn.addEventListener("click", onClick) — stackable handlers, unlike btn.onclick assignment.

2

Read the event object

e.target (origin), e.key (which key), e.clientX/Y (position) — details ride along automatically.

3

Control defaults and flow

e.preventDefault() stops native behavior (form submit, link nav); e.stopPropagation() halts bubbling.

4

Unsubscribe to clean

removeEventListener with the same function reference — named handlers clean up, anonymous ones can't.

$example
let count = 0;
function onClick(e) {
count++;
console.log("clicked", count, e.type);
}
document.querySelector("#btn").addEventListener("click", onClick, { once: false });
Output
(per click: clicked 1 click, clicked 2 click, ...)
1The named handler subscribes to button clicks — e arrives automatically per event.
2Each click increments and logs count plus the event type string.
3Named (not anonymous) so removeEventListener can detach it later.
$use cases
Click, input, and keyboard handling on controls
preventDefault for custom form submission and link behavior
Named handlers enabling later removal
once/passive/signal options for lifetime and scroll performance

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.