iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

DOM Events

A DOM event represents something that happened: a click, an input change, a finished resource load. JavaScript reacts via event listeners.

Categories

CategoryExamples
Mouse / touchclick, dblclick, mouseenter, mouseleave, contextmenu, pointerdown, touchstart
Keyboardkeydown, keyup, keypress (legacy)
Forminput, change, submit, focus, blur, invalid
LifecycleDOMContentLoaded, load, beforeunload, visibilitychange
Mediaplay, pause, ended, timeupdate
Drag / dropdragstart, dragover, drop
Windowscroll, resize, hashchange, online, offline

The event flow: capture → target → bubble

JS
// Default: listen on the bubble phase
parent.addEventListener("click", () => console.log("parent"));
child.addEventListener("click", () => console.log("child"));
// Click child → "child", "parent"

// Listen on capture instead
parent.addEventListener("click", fn, { capture: true });

// Stop propagation (don't reach the parent)
child.addEventListener("click", (e) => { e.stopPropagation(); });

// Prevent the browser default
form.addEventListener("submit", (e) => e.preventDefault());

The Event object

PropertyWhat it gives
e.typeEvent name (e.g. "click").
e.targetThe element that fired the event.
e.currentTargetThe element the listener is attached to.
e.preventDefault()Cancel the browser's default action.
e.stopPropagation()Don't bubble further.
e.key / e.code(KeyboardEvent) printed character / physical key.
Tip: Reach for event delegation (one listener on a parent) when the children are dynamic. Modern browsers can dispatch thousands of events a second through a single delegated listener.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from DOM Events!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Attach a click listener using the standard method.

btn. ('click', onClick);

Test yourself

Q1. Default phase listeners run in is…
Q2. Prevent the browser default action with…
Q3. `e.target` vs `e.currentTarget`…

Discussion

Loading…