이벤트 위임(event delegation)과 stopPropagation()

rada·2025년 4월 6일
0

개발

목록 보기
40/43

🏠 이벤트 위임(event delegation)과 stopPropagation()

✅ 예제

document.getElementById('container').addEventListener('click', function(e) {
  if (e.target.classList.contains("btn")) {
    console.log('button clicked');
    e.stopPropagation(); // 이벤트 버블링 중단
  }
});

document.body.addEventListener('click', function() {
  console.log('body clicked');
});
<body>
  <div id="container">
    <button class="btn">Click me</button>
  </div>
</body>

🔍 동작 설명:

  1. 버튼을 클릭하면 이벤트가 발생
  2. 이벤트는 버블링: button → div id="container" → body 순으로 전파됨

🧠 위임 + 조건 처리

  • container는 이벤트를 위임 받아서 자식 요소(.btn)의 클릭을 감지
  • e.target.classList.contains("btn") → 실제 클릭된 요소가 .btn인지 확인
  • 조건이 맞으면:
  • "button clicked" 출력
  • e.stopPropagation() → 이벤트가 body로 전파되지 않음

✅ 결과 로그:

버튼 클릭 시:

button clicked
  • body clicked는 출력되지 않음! (이벤트 전파가 중단되었기 때문)
  • container 내부 다른 영역 클릭 시 (.btn 아닌 곳):
body clicked

조건 통과 못하므로 stopPropagation()도 실행 안 됨 → 버블링 됨

🧠 핵심 요약

항목설명
이벤트 위임상위 요소에서 하위 요소의 이벤트를 감지
e.target실제 클릭된 요소
e.stopPropagation()이벤트 버블링 중단
.classList.contains()특정 클래스 있는지 확인
profile
So that my future self will not be ashamed of myself.

0개의 댓글