나는 프로그래머다!/HTML5
JavaScript - 이벤트 응용1 (버블링과 캡쳐링)
ironmask84
2015. 7. 28. 15:23
버블링과 캡쳐링은 addEventListener() 사용 시, 3번째 인자에 따라 구분된다.
true이면 캡쳐링이며, false 혹은 인자를 비워두면 버블링이다.
버블링 : 중첩된 태그에 등록된 이벤트를 가장 안쪽 태그부터 수행
캡쳐링 : 중첩된 태그에 등록된 이벤트를 가장 바깥쪽 태그부터 수행
웹브라우져 호환때문에도 그렇고, 거의 버블링을 사용한다.
http://output.jsbin.com/yozax/1/ <-- 웹 상에서 코드수정이 가능한 site 굿!
<html> <head> <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> </head> <body> <fieldset> <legend>event propagation</legend> <input type="button" id="target" value="target"> </fieldset> <script> function handler(event){ var phases = ['capturing', 'target', 'bubbling'] console.log(event.target.nodeName, this.nodeName, phases[event.eventPhase-1]); } 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); </script> </body></html>
위 코드에서 이벤트 실행 전파를 막는 방법도 있다.
아래의 핸들러를 정의한 후에 이벤트 등록 시에 사용하면 가능한다.
아래 코드를 추가 및 수정하면, body 태그의 이벤트 까지만 호출된다.
function stophandler(event){ var phases = ['capturing', 'target', 'bubbling'] console.log(event.target.nodeName, this.nodeName, phases[event.eventPhase-1]); event.stopPropagation();}document.querySelector('body').addEventListener('click', stophandler, false);
참고출처 : https://opentutorials.org/module/904/6768