DOM Events
A DOM event represents something that happened: a click, an input change, a finished resource load. JavaScript reacts via event listeners.
Categories
| Category | Examples |
|---|---|
| Mouse / touch | click, dblclick, mouseenter, mouseleave, contextmenu, pointerdown, touchstart |
| Keyboard | keydown, keyup, keypress (legacy) |
| Form | input, change, submit, focus, blur, invalid |
| Lifecycle | DOMContentLoaded, load, beforeunload, visibilitychange |
| Media | play, pause, ended, timeupdate |
| Drag / drop | dragstart, dragover, drop |
| Window | scroll, 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
| Property | What it gives |
|---|---|
e.type | Event name (e.g. "click"). |
e.target | The element that fired the event. |
e.currentTarget | The 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);
Three words concatenated.
Discussion
Loading…