<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<style>
html{border:5px solid red; padding:30px;}
body{border:5px solid green; padding:30px;}
fieldset{border:5px solid blue; padding:30px;}
input{border:5px solid black; padding:30px;}
</style>
</body>
<fieldset>
<legend>event propagation</legend>
<input type="button" id="target" value="target" />
</fieldset>
※ 상기 html코드를 모든 예제에 적용
function handler(event){
var phases = ['capturing', 'target', 'bubbling'];
console.log(event.target.nodeName, this.nodeName, phases[event.eventPhase-1]);
//.eventPhase : event 함수 호출 시 상태의 값. (1=capturing, 2=target, 3=bubbling)
}
/* bubbling */
document.getElementById('target').addEventListener('click', handler, false);
document.querySelector('fieldset').addEventListener('click', handler, false);
document.querySelector('body').addEventListener('click', handler, false);
document.querySelector('html').addEventListener('click', handler, false);
function handler(event){
var phases = ['capturing', 'target', 'bubbling'];
console.log(event.target.nodeName, this.nodeName, phases[event.eventPhase-1]);
//.eventPhase : event 함수 호출 시 상태의 값. (1=capturing, 2=target, 3=bubbling)
}
/* capturing */
document.getElementById('target').addEventListener('click', handler, true);
document.querySelector('fieldset').addEventListener('click', handler, true);
document.querySelector('body').addEventListener('click', handler, true);
document.querySelector('html').addEventListener('click', handler, true);
function stopHandler(event){
var phases = ['capturing', 'target', 'bubbling'];
console.log(event.target.nodeName, this.nodeName, phases[event.eventPhase-1]);
event.stopPropagation();
// stopPropagation() : event capturing/bubbling을 호출 단계에서 마무리할 떄 사용
}
document.getElementById('target').addEventListener('click', handler, false);
document.querySelector('fieldset').addEventListener('click', handler, false);
document.querySelector('body').addEventListener('click', stopHandler, false);
document.querySelector('html').addEventListener('click', handler, false);