Prevent default actions and stop propagation
Quick answer
preventDefault() requests cancellation of a cancelable event’s default action, provided the callback is not passive. stopPropagation() prevents dispatch from advancing to further targets; stopImmediatePropagation() also skips remaining callbacks at the current target. These controls are independent.
Browser examples
Run each snippet in a fresh browser document. These are static code blocks; ByteMind browser execution is not verified. Storage examples require a test origin.
const b=document.createElement("button");b.addEventListener("demo",e=>e.preventDefault());console.log(b.dispatchEvent(new Event("demo",{cancelable:true})),b.dispatchEvent(new Event("demo")));Expected console output:
false trueOnly the cancelable event can be canceled.
const p=document.createElement("div"),b=document.createElement("button");p.append(b);b.addEventListener("click",e=>{e.stopPropagation();console.log("first");});b.addEventListener("click",()=>console.log("second"));p.addEventListener("click",()=>console.log("parent"));b.click();Expected console output:
firstsecondThe second listener runs on the same target, but the parent does not.
Common mistake
Calling preventDefault does not automatically stop bubbling, and stopping propagation does not cancel the default action.
Practice
Change the example to use stopImmediatePropagation and predict which sibling listener executes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Prevent default actions and stop propagation — Knowledge Check
Apply the concept and predict the browser example behavior.
Which method also skips later listeners in the current invocation group?
Does preventDefault cancel a noncancelable event?
What does dispatchEvent return when a cancelable event was canceled?
What is the exact console output in Prevent default actions and stop propagation example 1?
const b=document.createElement("button");b.addEventListener("demo",e=>e.preventDefault());console.log(b.dispatchEvent(new Event("demo",{cancelable:true})),b.dispatchEvent(new Event("demo")));What is the exact console output in Prevent default actions and stop propagation example 2?
const p=document.createElement("div"),b=document.createElement("button");p.append(b);b.addEventListener("click",e=>{e.stopPropagation();console.log("first");});b.addEventListener("click",()=>console.log("second"));p.addEventListener("click",()=>console.log("parent"));b.click();