e.preventDefault() vs e.stopPropagation()

작성자

카테고리:

← 피드로
DEV Community · Harsh vardhan Prasad · 2026-08-12 개발(SW)

Harsh vardhan Prasad

The easiest way to remember it:
preventDefault() → stops the browser’s default action.
stopPropagation() → stops the event from moving through the DOM.

  1. 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();

  1. 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:



Like

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.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다