DOM Events
Events are the browser's way of telling your code that something happened: a click, a key press, a form submission, a page scroll. The JS Events chapter showed the basics; this chapter looks at how events actually travel through the DOM, what the event object contains, and how to cancel default behaviour.
Event categories
| Category | Examples |
|---|---|
| Mouse / pointer | click, dblclick, contextmenu, pointerdown, pointermove, mouseenter, mouseleave |
| Keyboard | keydown, keyup |
| Form | input, change, submit, focus, blur, reset |
| Document / window | DOMContentLoaded, load, resize, scroll, beforeunload |
| Clipboard / drag | copy, paste, dragstart, drop |
The event object
Every handler receives an event object with details about what happened. Some properties exist on every event; others depend on the type:
| Property | Meaning |
|---|---|
type |
the event name, e.g. "click" |
target |
the element where the event originated (e.g. the exact element clicked) |
currentTarget |
the element whose listener is currently running |
timeStamp |
when it happened |
key, code |
(keyboard) the character / the physical key |
clientX, clientY |
(mouse) pointer position in the viewport |
shiftKey, ctrlKey, altKey, metaKey |
modifier keys held down |
<style>#pad { height: 120px; border: 2px dashed #999; border-radius: 8px; padding: 8px; user-select: none; }</style>
<div id="pad" tabindex="0">Click here (try holding Shift), then type some keys.</div>
<p id="out">…</p>
<script>
const pad = document.getElementById("pad");
const out = document.getElementById("out");
pad.addEventListener("click", (e) => {
out.textContent = `${e.type} at (${e.offsetX}, ${e.offsetY})${e.shiftKey ? " with Shift" : ""}`;
pad.focus();
});
pad.addEventListener("keydown", (e) => {
out.textContent = `key="${e.key}" code="${e.code}"`;
console.log("keydown:", e.key);
});
</script>Bubbling: events travel up the tree
When you click a button inside a <div> inside a <section>, the click doesn't only happen on the button. After the button's handlers run, the event bubbles up to each ancestor in turn — the div, the section, the body, the document — and their click handlers run too:
<style>
div { padding: 12px; margin: 4px; border: 2px solid; border-radius: 8px; }
#outer { border-color: #c33; } #middle { border-color: #393; } #inner { border-color: #36c; }
</style>
<div id="outer">outer
<div id="middle">middle
<div id="inner">inner — click me</div>
</div>
</div>
<script>
for (const id of ["outer", "middle", "inner"]) {
document.getElementById(id).addEventListener("click", (e) => {
console.log(`${id} handler: target=${e.target.id}, currentTarget=${e.currentTarget.id}`);
});
}
</script>Click "inner" and you'll see three lines: inner, then middle, then outer. target stays the same (where the click started), while currentTarget changes as the event bubbles.
Before bubbling there is also a capturing phase that goes down from the document to the target. You rarely need it, but you can listen during capture with addEventListener(type, fn, { capture: true }).
Stopping propagation
event.stopPropagation() stops the event from reaching any further ancestors. Use it sparingly — other code (analytics, menus that close on outside clicks) may rely on bubbling:
<style> .card { border: 1px solid #ccc; padding: 10px; border-radius: 8px; cursor: pointer; } </style>
<div class="card" id="card">
<b>Product card</b> — clicking the card opens details.
<button id="fav">♡ Favourite</button>
</div>
<script>
document.getElementById("card").addEventListener("click", () => {
console.log("open product details");
});
document.getElementById("fav").addEventListener("click", (e) => {
e.stopPropagation(); // don't also open the details
e.currentTarget.textContent = "♥ Favourited";
console.log("added to favourites");
});
</script>Preventing the default action
Many events trigger built-in browser behaviour: links navigate, forms submit, checkboxes toggle, right-click opens a menu, and some keys scroll the page. event.preventDefault() cancels that behaviour (it does not stop bubbling):
<a href="https://example.com" id="link">A link that doesn't navigate</a>
<p><input id="digits" placeholder="Digits only"></p>
<div id="area" style="padding:20px;background:#eef">Right-click me</div>
<script>
document.getElementById("link").addEventListener("click", (e) => {
e.preventDefault();
console.log("navigation cancelled for", e.currentTarget.href);
});
document.getElementById("digits").addEventListener("keydown", (e) => {
const allowed = ["Backspace", "Delete", "ArrowLeft", "ArrowRight", "Tab"];
if (!/^\d$/.test(e.key) && !allowed.includes(e.key)) {
e.preventDefault(); // block the character
console.log(`blocked "${e.key}"`);
}
});
document.getElementById("area").addEventListener("contextmenu", (e) => {
e.preventDefault();
e.currentTarget.textContent = "Custom menu would open here!";
});
</script>Page lifecycle events
| Event | Fires when |
|---|---|
DOMContentLoaded (on document) |
the HTML is parsed and the DOM is ready |
load (on window) |
everything, including images and stylesheets, has loaded |
beforeunload / pagehide |
the user is leaving the page |
With <script type="module"> or defer, your code already runs after the DOM is ready, so you rarely need DOMContentLoaded.
Test yourself
During bubbling, which property always refers to the element where the event started?
- currentTarget
- target
- this
- srcElement only
What does event.preventDefault() do?
- Stops bubbling
- Cancels the browser's default action
- Removes the listener
- Prevents other handlers on the same element
In which order do click handlers run when you click a button inside a div (both have handlers)?
- div, then button
- button, then div
- Only the button
- Only the div