[JavaScript] Event Bubbling & Capturing

Steve·2021년 6월 15일
0

공부

목록 보기
10/10

Event bubbling

한 엘리먼트에 이벤트가 일어나면, 엘리먼트의 이벤트 핸들러를 실행하고, 그 다음 부모 엘리먼트의 이벤트 핸들러, 그리고 root 엘리먼트(document object)의 이벤트 핸들러까지 실행되는 것.

예시)

<form onclick="alert('form')">
  FORM
  <div onclick="alert('div')">
    DIV
    <p onclick="alert('p')">P</p>
  </div>
</form>

// P 를 클릭하면 <p>, <div>, <form> 의 이벤트 핸들러가 차례대로 실행된다.

거품이 일어나서 커지는 것처럼 내부의 엘리먼트에서부터 부모 엘리먼트로 이벤트가 실행된다.

event.target

이벤트의 원인이 된 엘리먼트를 target element 라고 하며, event.target 으로 access 할 수 있다.

Stopping bubbling

이벤트 버블링은 target 엘리먼트에서 -> <html>, document 객체, 심지어는 window객체까지 가는 이벤트도 있으며, 가는 길의 모든 핸들러를 호출한다.

버블링을 멈추게 하려면 event.stopPropagation() 을 사용한다.
event.stopImmediatePropagation() 엘리먼트의 모든 핸들러의 bubbling 을 막고 싶을 때.

<body onclick="alert(`the bubbling doesn't reach here`)">
  <button onclick="event.stopPropagation()">Click me</button>
</body>

// 버튼을 눌러도 이벤트가 발생하지 않는다.

보통 bubbling 을 멈추게 만들 이유는 거의 없다.

Event capturing

Capturing 은 거의 사용되지 않긴 하다.

DOM 이벤트 전파는 3 단계가 있다.

  1. Capturing phase – the event goes down to the element.
  2. Target phase – the event reached the target element.
  3. Bubbling phase – the event bubbles up from the element.


이미지: https://www.w3.org/TR/DOM-Level-3-Events/

이벤트가 발생하면 먼저 조상 엘리먼트에서 target 엘리먼드로 가고, 이벤트가 발생, 그 후 다시 위로 핸들러를 호출시킨다. Capturing phase 는 invisible 하다.

profile
게임과 프론트엔드에 관심이 많습니다.

0개의 댓글