이벤트 객체의
target
프로퍼티는 실제로 이벤트를 발생시킨 DOM 요소를 가리키며, 이벤트 객체의currentTarget
프로퍼티는 이벤트 핸들러가 바인딩된 DOM요소를 가리킨다.
일반적으로 이벤트 객체의target
프로퍼티와currentTaget
프로퍼티는 동일한 DOM 요소를 가리키지만 서로 다른 DOM 요소를 가리킬 수 있다.
<div id="parent">
Click parent
<div id="child">Click child</div>
</div>
<button id="reset">Reset</button>
<pre id="output"></pre>
const output = document.querySelector("#output");
const parent = document.querySelector("#parent");
parent.addEventListener("click", (event) => {
const currentTarget = event.currentTarget.getAttribute("id");
const target = event.target.getAttribute("id");
output.textContent = `Current target: ${currentTarget}\n`;
output.textContent += `Target: ${target}`;
});
const reset = document.querySelector("#reset");
reset.addEventListener("click", () => document.location.reload());
이렇게 child 클릭시,
target
은 실제로 눌러서 발생된 child가 된다. child는 상위 DOM 요소인 parent의 이벤트 위임
을 받기때문에 상위요소에 있는 eventListener가 child에도 동작하게 되므로 child가 event.target
으로 반환 되는 것이다.
currentTarget
은 발생한 이벤트가 등록된(이벤트 핸들러가 바인딩된) Parent가 된다. 왜 그런걸까?
버블링 이벤트 때문이다.
버블링 단계(bubbling phase)
는 이벤트가 하위 요소에서 상위 요소로 전파되는 단계이다.
한 요소에 이벤트가 발생하면 이 요소에 할당된 핸들러가 동작하고, 이어서 부모 요소의 핸들러가 동작한다. 가장 최상단의 조상 요소를 만날때까지 이 과정이 반복되면서 요소 각각에 할당된 핸들러가 동작한다.
그렇기 때문에 child => parent 순서대로 이벤트가 발생되고, 버블링 이벤트가 적용된 상위요소를 반환해 event.currentTarget
은 parent가 되는 것이다. ☻
<참고>
https://ko.javascript.info/bubbling-and-capturing
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget