* 이벤트(Event)
- 키보드 입력, 마우스 클릭과 같이 다른 것에 영향을 미치는 것을 의미
- 마우스 이벤트, 키보드 이벤트, HTML 프레임 이벤트, HTML 입력 양식 이벤트, 유저 인터페이스 이벤트, 구조 변화 이벤트, 터치 이벤트
1. 이벤트 관련 용어
<script type="text/javascript"> window.onload = function() {}; </script>
- 이벤트 연결 : window 객체의 onload 속성에 함수 자료형을 할당하는 것
- 이벤트 이름(타입) : load
- 이벤트 속성 : onload
- 이벤트 리스너(핸들러) : 이벤트 속성에 할당한 함수
- 이벤트 모델 : 문서 객체에 이벤트를 연결하는 방법, DOM Level 단계에 따라 두가지로 분류하고 각기 두가지로 또 나뉨
2. DOM Level 0
- 인라인 이벤트 모델
- 기본 이벤트 모델
2.1. 고전 이벤트 모델
- 문서 객체의 이벤트 속성으로 이벤트를 연결하는 방법
- 이벤트 하나에 이벤트 리스너 하나만 연결 가능
<!-- event.html --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>event</title> <script type="text/javascript"> window.onload = function() { var header = document.getElementById('header'); // header 객체에 onclick 이벤트 속성을 연결 header.onclick = function() { alert('클릭'); // 이벤트를 제거, 한번만 실행이 됨 header.onclick = null; } }; </script> </head> <body> <h1 id="header">Click</h1> </body> </html>
2.2. 이벤트 발생 객체와 이벤트 객체
- 이벤트 리스너 안에서 this 키워드를 사용하면 이벤트가 발생한 객체를 찾을 수 있음
- this 키워드의 스타일을 바꾸면 이벤트가 발생한 객체의 스타일을 변경하는 것과 같음
<!-- event2.html --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>event2</title> <script type="text/javascript"> window.onload = function() { document.getElementById('header').onclick = function() { this.style.color = 'red'; } }; </script> </head> <body> <h1 id="header">Click</h1> </body> </html>
2.3. 이벤트 강제 실행
- 메서드를 호출하는 것처럼 이벤트 속성을 호출
<!-- event3.html --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>event3</title> <script type="text/javascript"> window.onload = function() { var button1 = document.getElementById('button1'); var button2 = document.getElementById('button2'); var counter1 = document.getElementById('counter1'); var counter2 = document.getElementById('counter2'); button1.onclick = function() { counter1.innerHTML = Number(counter1.innerHTML) + 1; }; button2.onclick = function() { counter2.innerHTML = Number(counter2.innerHTML) + 1; // button2 를 클릭하면 button1 클릭한 이벤트도 발생 button1.onclick(); }; }; </script> </head> <body> <button id="button1">ButtonA</button> <button id="button2">ButtonB</button> <h1>Button 1 - <span id="counter1">0</span></h1> <h1>Button 2 - <span id="counter2">0</span></h1> </body> </html>
2.4. 인라인 이벤트 모델
- HTML 페이지의 가장 기본적인 이벤트 연결 방법
<!-- event4.html --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>event4</title> <script type="text/javascript"> function whenClick(e) { alert('클릭3'); } </script> </head> <body> <h1 onclick="alert('클릭1')">Click1</h1> <h1 onclick="var alpha='클릭2'; alert(alpha);">Click2</h1> <h1 onclick="whenClick(event)">Click3</h1><!-- event 객체 전달 --> </body> </html>
2.5. 디폴트 이벤트 제거
- 일부 HTML 태그는 이미 이벤트 리스너가 존재 이것을 디폴트 이벤트라고 함
- 이벤트 리스너에서 false를 리턴
- 인라인 이벤트 모델은 form 태그의 onsubmit 이벤트 속성에 return 메서드() 형태를 입력
<!-- event5.html --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>event5</title> <script type="text/javascript"> window.onload = function() { document.getElementById('memberForm').onsubmit = function() { return false; }; }; function whenSubmit() { return false; } </script> </head> <body> <form id="memberForm"> <input type="text" id="id" name="id" placeholder="아이디"><br> <input type="password" id="pwd" name="pwd" placeholder="비밀번호"><br> <input type="text" id="email" name="email" placeholder="이메일"><br> <input type="submit" value="제출"> </form> <hr> <form onsubmit="return whenSubmit()"> <input type="text" id="id" name="id" placeholder="아이디"><br> <input type="password" id="pwd" name="pwd" placeholder="비밀번호"><br> <input type="text" id="email" name="email" placeholder="이메일"><br> <input type="submit" value="제출"> </form> </body> </html>
2.6. 이벤트 전달
- 어떠한 이벤트가 먼저 발생해서 어떤 순서로 발생하는지
- 이벤트 버블링 : 자식 노드에서 부모 노드 순으로 이벤트 실행
- 이벤트 캡쳐링 : 부모 노드에서 자식 노드 순으로 이벤트 실행 (익스플로러와 jQuery는 미지원)
<!-- event6.html --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>event6</title> <script type="text/javascript"> window.onload = function() { document.getElementById('h').onclick = function () { alert('h'); }; document.getElementById('p').onclick = function () { alert('p'); }; }; </script> </head> <body> <h1 id="h"> <!-- p 태그를 클릭하면 이벤트 버블링으로 인해 경고창이 p > h 순으로 출력 --> <p id="p">p</p> </h1> </body> </html>
- 익스플로러와 그외 브라우저가 이벤트 전달을 막는 방법
- 익스플로러 : 이벤트 객체의 cancelBubble 속성을 true로 변경
- 그 외 브라우저 : 이벤트 객체의 stopPropagation() 메서드를 사용
<!-- event7.html --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>event7</title> <script type="text/javascript"> window.onload = function() { document.getElementById('h').onclick = function() { alert('h'); }; document.getElementById('p').onclick = function(e) { var event = e || window.event; alert('p'); event.cancleBubble = true; if (event.stopPropagation) { event.stopPropagation(); } }; }; </script> </head> <body> <h1 id="h"> <!-- p 태그를 클릭하면 이벤트 버블링으로 인해 경고창이 p > h 순으로 출력되는 도중에 이벤트 전달을 제거 --> <p id="p">p</p> </h1> </body> </html>
3. DOM Level 2
- 마이크로소프트 인터넷 익스플로러 이벤트 모델
- 표준 이벤트 모델
3.1. 인터넷 익스플로러 이벤트 모델
- 두 가지 메서드로 이벤트를 연결하거나 제거할 수 있음
- 여러번 이벤트를 추가 할 수 있음
- 첫 번째 매개변수에 이벤트 속성을 넣어줌
- attachEvent(eventProperty, eventListener);
- detachEvent(eventProperty, evetListener);
- 이벤트 리스너 안에서 this 키워드가 window 객체를 의미
3.2. 표준 이벤트 모델
- W3C에서 공식적으로 지정
- 한번에 여러가지 이벤트 리스너를 추가 가능
- 이벤트 캡쳐링 지원하지만 사용하지 않음
- addEventListener(eventName, handler, useCapture)
- removeEventListener(eventName, handler)
- 매개변수 useCapture는 입력하지 않으면 자동으로 false
- 이벤트 리스너 안에서 this 키워드가 이벤트 발생 객체를 의미
<!-- event9.html --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>event9</title> <script type="text/javascript"> window.onload = function () { var header = document.getElementById('header'); // 익스플로러 실행 if (header.attachEvent) { var handler = function() { window.event.srcElement.style.color = 'red'; window.event.srcElement.detachEvent('onclick', handler); }; header.attachEvent('onclick', handler); // 그 이외의 브라우저 실행 } else { var handler = function() { this.style.color = 'red'; this.removeEventListener('click', handler); }; header.addEventListener('click', handler); } // if }; </script> </head> <body> <h1 id="header">header</h1> </body> </html>
'Web > JavaScript' 카테고리의 다른 글
자바스크립트(JavaScript) 외부 자바스크립트 파일 (0) | 2013.11.25 |
---|---|
자바스크립트(JavaScript) 예외 처리(Exception handling) (3) | 2013.11.25 |
자바스크립트(JavaScript) 문서 객체 모델(DOM : Document Object Model) (0) | 2013.11.19 |
자바스크립트(JavaScript) 브라우저 객체 모델(Browser Object Model) (0) | 2013.11.19 |
자바스크립트(JavaScript) 메서드 체이닝(Method Chaining) (0) | 2013.11.18 |