preventDefault Stops Actions, stopPropagation Stops Travel
event.preventDefault cancels the default action while other listeners still run; stopPropagation blocks other listeners while the default action proceeds.
Code
// preventDefault cancels the default action; the event keeps traveling
const form = document.createElement("form");
document.body.append(form);
document.addEventListener("submit", () => console.log("listener still runs"));
form.addEventListener("submit", (event) => {
event.preventDefault();
console.log("defaultPrevented:", event.defaultPrevented);
});
form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
// stopPropagation 阻断传播,默认动作不受影响
const button = document.createElement("button");
document.body.append(button);
document.addEventListener("click", () => console.log("doc saw click"));
button.addEventListener("click", (event) => {
event.stopPropagation();
console.log("button clicked, defaultPrevented:", event.defaultPrevented);
});
button.click();How it works
Top-level bindings form, button hold the demo state — nothing sits inside a function scope.
Watch out for
documentexist only in browsers — a Node runtime has no shims for them out of the box.
Using it
The run emits 4 labeled sections — listener still runs, defaultPrevented:, doc saw click, button clicked, defaultPrevented: — one per step.
Key statements
button.addEventListener("click", (event) => {
event.stopPropagation();
console.log("button clicked, defaultPrevented:", event.defaultPrevented);
});
form.addEventListener("submit", (event) => {
event.preventDefault();
console.log("defaultPrevented:", event.defaultPrevented);
});
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does preventDefault Stops Actions, stopPropagation Stops Travel run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.