The easiest way to remember it:
preventDefault() → stops the browser’s default action.
stopPropagation() → stops the event from moving through the DOM.
- event.preventDefault() It prevents the browser’s built-in behavior associated with an event. Example: clicking a link. Google
document.getElementById(“link”).addEventListener(“click”, (event) => {
event.preventDefault();
});
Normally:
Click
↓
Browser navigates to Google
With preventDefault():
Click
↓
preventDefault()
↓
❌ Browser does NOT navigate
Common uses:
// Form submission
event.preventDefault();
// Link navigation
event.preventDefault();
// Drag/drop browser behavior
event.preventDefault();
- event.stopPropagation() This prevents the event from bubbling up or capturing down through parent/child elements. Example: Click me parent.addEventListener(“click”, () => { console.log(“Parent clicked”); });
child.addEventListener(“click”, (event) => {
event.stopPropagation();
console.log(“Button clicked”);
});
Without stopPropagation():
Click Button
↓
Button handler
↓
Parent handler
Output:
Button clicked
Parent clicked
With stopPropagation():
Click Button
↓
Button handler
↓
stopPropagation()
↓
❌ Parent handler doesn’t receive the event
The important difference
Imagine:
If you click the button:
preventDefault()
button.addEventListener(“click”, (event) => {
event.preventDefault();
});
The event can still propagate:
Button
↓
Anchor
↓
Card
But the browser’s default action (such as following the link) is prevented.
stopPropagation()
button.addEventListener(“click”, (event) => {
event.stopPropagation();
});
The event doesn’t continue through the DOM:
Button
↓
❌ Anchor/Card handlers
But the browser’s default behavior is not automatically cancelled.
Can you use both?
Yes.
button.addEventListener(“click”, (event) => {
event.preventDefault();
event.stopPropagation();
});
Now you’re saying:
Don’t perform the browser’s default action.
Don’t let this event reach other elements.
답글 남기기