본문 바로가기

Frontend/Java Script

JS event (part. 06) - 이벤트 전달

<h1 id="header">
  <p id="paragraph">Paragraph</p>
</h1>

 

window.onload = function () {
  document.getElementById('header').onclick = function () {
    alert('header');
  };
  document.getElementById('paragraph').onclick = function () {
    alert('paragraph');
  };
};

 

p 태그를 클릭하면 이벤트 버블링이 일어나면서 paragraph => header 순으로 경고창이 출력됨

여기서 이벤트의 전달을 막아보자

 

인터넷 익스플로러와 그외 브라우저가 이벤트 전달을 막는 방법이 다름

  • 인터넷 익스플로러 : 이벤트 객체의 cancelBubble 속성을 true로 변경
  • 그 이외의 브라우저 : 이벤트 객체의 stopPropagation() 메서드 사용
window.onload = function () {
  document.getElementById('header').onclick = function () {
    alert('header');
  };

  document.getElementById('paragraph').onclick = e => {
    var event = e || window.event;

    alert('paragraph');
    
	// 인터넷 익스플로러
    event.cancelBubble = true;
    
     // 그 이외의 브라우저
    if (event.stopPropagation) {
      event.stopPropagation(); 
    }
  };
};