
| 기준 | 이벤트 버블링 | 이벤트 캡처링 |
|---|---|---|
| 전파 방향 | 자식 요소에서 시작해 부모 요소로 이동 | 최상위 요소에서 시작해 목표 요소(이벤트가 발생한 요소)로 이동 |
| 사용 목적 | 하위 요소에서 발생한 이벤트를 상위 요소에서 처리할 수 있게 함 | 상위 요소에서 하위 요소로 이벤트를 전달하기 전에 미리 처리할 수 있게 함 |
| 기본 동작 | 기본적으로 활성화되어 있음 | 명시적으로 설정해야 활성화됨 (addEventListener의 세 번째 인자로 true 설정) |
| 주 사용 사례 | 이벤트 위임과 같이 여러 자식 요소에 공통적인 이벤트 핸들러를 적용할 때 유용 | 특정 이벤트를 가로채서 특별한 처리를 하기 전에 미리 캡처링할 때 유용 |
| 중단 방법 | stopPropagation() 메서드를 사용하여 이벤트 버블링 중단 | stopPropagation() 메서드를 사용하여 이벤트 캡처링 중단 |
| 주의 사항 | 부모 요소에 이벤트가 전달되기 때문에 불필요한 이벤트 처리가 발생할 수 있음 | 캡처링 단계에서 이벤트를 처리하면 하위 요소에서는 이벤트를 감지할 수 없게 될 수 있음 |
<!DOCTYPE html>
<html>
<head>
<title>이벤트 버블링 예제</title>
</head>
<body>
<div id="parent" style="width: 200px; height: 200px; background-color: #f2f2f2;">
부모
<div id="child" style="width: 100px; height: 100px; background-color: #a1a1a1; margin-top: 20px;">
자식
</div>
</div>
<script>
// 부모 요소에 이벤트 리스너 추가
document.getElementById('parent').addEventListener('click', function(event) {
alert('부모 요소가 클릭되었습니다. 이벤트 발생 요소: ' + event.target.id);
});
// 자식 요소에 이벤트 리스너 추가
document.getElementById('child').addEventListener('click', function(event) {
alert('자식 요소가 클릭되었습니다.');
});
</script>
</body>
</html>
하위 요소에서 발생하는 이벤트를 감지할 때
document.getElementById('parent').addEventListener('click', function() {
console.log('부모에서 캡처링');
}, true);
<!DOCTYPE html>
<html>
<head>
<title>이벤트 버블링 예제</title>
</head>
<body>
<div
id="parent"
style="width: 200px; height: 200px; background-color: #f2f2f2"
>
부모
<div
id="child"
style="
width: 100px;
height: 100px;
background-color: #a1a1a1;
margin-top: 20px;
"
>
자식
</div>
</div>
<script>
// 부모 요소에 이벤트 리스너 추가
document.getElementById("parent").addEventListener(
"click",
function (event) {
alert(
"부모 요소가 클릭되었습니다. 이벤트 발생 요소: " + event.target.id
);
},
true
);
// 자식 요소에 이벤트 리스너 추가
document
.getElementById("child")
.addEventListener("click", function (event) {
alert("자식 요소가 클릭되었습니다.");
});
</script>
</body>
</html>
stopPropagation() : 이 메서드를 이벤트 처리 함수 내에서 호출하면, 해당 이벤트의 콜백을 실행한 뒤 이후에 진행되는 버블링과 캡처링이 중단된다. 이를 통해 불필요한 이벤트 전파를 방지할 수 있다. 이벤트 발생 순서의 흐름을 차단하는 것이다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Event Delegation Example</title>
<style>
/* 타겟 범위를 확인하기 위한 표시 */
li {
border: 1px solid red;
cursor: pointer;
margin: 10px;
}
</style>
</head>
<body>
<ul id="itemsList">
<li>아이템 1</li>
<li>아이템 2</li>
<li>아이템 3</li>
<li>아이템 4</li>
</ul>
<script>
// 이벤트 위임을 사용하여 UL 요소에 이벤트 리스너를 추가합니다.
document
.getElementById("itemsList")
.addEventListener("click", function (event) {
// event.target은 클릭된 요소입니다.
// 이 예제에서는 LI 요소가 클릭되면 그 요소에 대한 정보를 가져옵니다.
if (event.target.tagName === "LI") {
// 태그 이름이 LI인지 확인합니다.
alert(event.target.textContent + "가 클릭되었습니다.");
}
});
</script>
</body>
</html>
event.target으로 이벤트가 발생한 타겟을 참조할 수 있다.