이벤트 모델의 종류

  • DOM Level 0
    • 인라인 이벤트 모델
    • 고전 이벤트 모델 = 기본 이벤트 모델

 

  • DOM Level 2
    • 표준 이벤트 모델

 

 

인라인 이벤트 모델

  • 인라인 이벤트 모델 : HTML 태그의 프로퍼티를 사용하여 이벤트를 작성하는 방식
    ⚠️ 비표준이므로 권장하지 않음

 

  • 태그에 이벤트를 직접 작성
<input type="button" value="이동" onclick="location.href='https://www.naver.com';">
<input type="button" value="확인" onclick="alert('클릭 이벤트 발생!');">

 

  • 태그에서 함수를 호출하여 이벤트 처리
function whenClick() {
	alert('클릭 이벤트 발생!');
}
<body>
	<div id="header" onclick="whenClick();">클릭</div>
</body>

 

 

이벤트 타입(Event Type)

  • onclick : 클릭했을 때
function changeColor(color) {
	document.body.style.backgroundColor = color;
}
<body>
	<form>
		<input type="radio" name="color" value="blue" onclick="changeColor('lightblue')">파란색
		<input type="radio" name="color" value="greem" onclick="changeColor('lightgreen')">녹색
		<input type="radio" name="color" value="white" onclick="changeColor('white')">흰색
	</form>
</body>

 

  • onmouseover : 커서를 올려놓을 때
  • onmouseout : 커서를 떼었을 때
function changeBgColor(cell, newColor) {
	cell.style.backgroundColor = newColor;
}
<body>
<table>
	<tr>
		<!-- this는 이벤트가 발생한 태그를 의미함 -->
		<td onmouseover="changeBgColor(this,'yellow');" onmouseout="changeBgColor(this,'gray')">
			<a href="#">[Menu1]</a>
		</td>
	</tr>
	<tr>
		<td onmouseover="changeBgColor(this,'yellow');" onmouseout="changeBgColor(this,'gray')">
			<a href="#">[Menu2]</a>
		</td>
	</tr>
	<tr>
		<td onmouseover="changeBgColor(this,'yellow');" onmouseout="changeBgColor(this,'gray')">
			<a href="#">[Menu3]</a>
		</td>
	</tr>
</table>
</body>

 

  • onchange : 상태가 바뀔 때
function sub() {
	var capital = document.getElementById('name');
	// 대문자로 변환한 후 입력 필드에 표시
	capital.value = capital.value.toUpperCase();     // value : name에 입력된 데이터
}
<body>
대문자 변환 : <input type="text" id="name" onchange="sub();">
<p>입력 필드를 벗어나면 대문자로 변경됩니다.</p>
</body>

 

  • onsubmit : <form>에서 submit 이벤트가 발생했을 때
    ⭐ onsubmit 속성을 이용하여 자바스크립트에서 유효성 체크를 할 수 있다.
function check() {
	// 아이디가 입력되지 않은 경우
	if(document.member.id.value=='') {	
		alert('아이디를 입력하세요!');
        
        // 아이디 필드로 커서 이동
		document.member.id.focus();
        
        // submit 이벤트가 발생하지 않도록 처리
		return false;			
	}
    
	// 비밀번호가 입력되지 않은 경우
	if(document.member.password.value=='') {
		alert('비밀번호를 입력하세요!');
		document.member.password.focus();
		return false;
	}
}
<body>
						<!-- check()의 반환값이 true이면 처리 -->
<form name="member" action="a.jsp" method="post" onsubmit="return check();">
	ID <input type="text" name="id"><br>
	비밀번호 <input type="password" name="password"><br>
	<input type="submit" value="확인">
	<input type="reset" value="초기화">
</form>
</body>

 

  • isNaN( ) 메소드를 이용한 유효성 체크
    ⭐ isNaN( )은 공백을 0으로 인식하므로 공백을 제거한 뒤 검증해야 함
function checkAge() {
	var age = document.getElementById('age');
	
	// 1. 입력을 안했을 경우 : 공백 제거를 위해 trim() 이용
	if(age.value.trim() == ''){
		alert('나이를 입력하세요!');
		age.focus();
		return;
	}
	
	// 2. 문자를 입력했을 경우
	if(isNaN(age.value)){
		alert('숫자만 입력 가능!');
		age.focus();
		return;
	}
	alert('나이는 ' + age.value + '살입니다.'); 
}
<body>
<form>
	나이 <input type="text" name="age" id="age" size="20">
	<input type="button" value="확인" onclick="checkAge();">
</form>
</body>

 

 

고전 이벤트 모델

  • 고전 이벤트 모델 : 자바스크립트 내부에서 이벤트를 연결하는 방식 (=기본 이벤트 모델)

 

  • 이벤트 핸들러(Event Handler) : 이벤트가 발생하면 처리되는 함수 (=이벤트 리스너(event listener))

 

  • 이벤트 핸들러로 선언적 함수 연결
    ⭐ 함수명만 작성해야 함
window.onload = function() {
	var header = document.getElementById('header');
	
	function whenClick() {
		alert('클릭 이벤트 발생!');
	}
	
	// 이벤트	이벤트 핸들러
	header.onclick = whenClick;
};
<body>
	<div id="header">클릭</div>
</body>

 

  • 이벤트 핸들러로 익명 함수 연결
    ⭐ 익명함수를 이용하면 코드가 간결해지고 실수를 줄일 수 있다.
window.onload = function() {
	var header = document.getElementById('header');

	// 이벤트	이벤트 핸들러
	header.onclick = function() {
		alert('클릭 이벤트 발생!');
	};
};
<body>
	<div id="header">클릭</div>
</body>

 

 

키보드 이벤트(key Event)

  1. keydown : 키보드가 눌러질 때
  1. keypress : 글자가 입력될 때(한글 사용불가)
  1. keyup : 키보드가 떼어질 때

 

  • onkeyup : 한글은 자모음을 결합하여 작성되므로 keyup 이벤트를 주로 사용
window.onload = function() {
	var content = document.getElementById('content');
	// keyup 이벤트 연결
	content.onkeyup = function() {
		// 입력한 글자 수
		var inputLength = this.value.length;
		// 남은 글자 수 계산
		var remain = 150 - inputLength;
		
		var letter = document.getElementById('letter');
		letter.innerHTML = remain;	// 태그에 출력
	};
};
<body>
	<h4 id="letter">150</h4>
	<textarea rows="5" cols="30" name="content" id="content"></textarea>
</body>

 

 

기본 이벤트 변형

  • 기본 이벤트를 변형한 이벤트 처리 : <a> <form> 태그는 기본 이벤트를 가지고 있음
window.onload = function() {
	var alink = document.getElementById('alink');
	// click 이벤트 연결
	alink.onclick = function() {
		alert('클릭 이벤트 발생!');
		
		// a 태그의 기본 이벤트 제거
		return false;
	};
	
	var myForm = document.getElementById('myForm');
	// submit 이벤트 연결
	myForm.onsubmit = function() {
		var name = document.getElementById('name');
		alert(name.value);
		
		// form태그의 기본 이벤트 제거
		return false;
	};
};
<body>
<a id="alink" href="https://www.naver.com">클릭</a>
<br><br>
<form id="myForm" action="a.jsp" method="post">
	이름 <input type="text" name="name" id="name">
	<input type="submit" value="전송">
</form>
</body>

 

 

이벤트 전파(Event Propagation)

  • 이벤트 전파 방식
    1. 이벤트 버블링(bubbling) : 이벤트가 자식노드 → 부모노드 순으로 전파
    2. 이벤트 캡쳐링(capturing) : 이벤트가 부모노드 → 자식노드 순으로 전파 / 비 IE 브라우저 지원

 

  • 자식 노드로의 이벤트 전파 막기 - 버블링 방식
window.onload = function() {
	var header = document.getElementById('header');
	// 이벤트 연결
	header.onclick = function() {
		alert('header');
		this.style.backgroundColor = 'pink';
	};

	var paragraph = document.getElementById('paragraph');
	// 이벤트 연결 - 이벤트 객체를 전달받기 위해 event 라는 매개변수를 명시
	paragraph.onclick = function(event) {
		alert('paragraph');
		this.style.backgroundColor = 'yellow';
		
		// 이벤트 전파 막기
		event.stopPropagation();
	};
};
<body>
	<h1 id="header">부모 태그
		<p id="paragraph">자식 태그</p>
	</h1>
</body>

 

 

표준 이벤트 모델

  • DOM Level 2의 이벤트 모델
  • 인라인 방식(태그 내)보다 스크립트 내에 명시하는 방식을 선호한다.
  • window.onload 대신 EventListenter 메소드를 사용한다.

 

  • addEventListenter(eventType, eventHandler, useCapture) : 이벤트 연결
    • useCapture : true 캡쳐링 방식, false 버블링 방식
  • removeEventListener(evenType, eventHandler) : 이벤트 제거
// 문서가 로드될 때 (onload)
window.addEventListener('load',function(){
	var header = document.getElementById('header');
    
	// click 이벤트 연결
	header.addEventListener('click',function(){
		alert('이벤트 발생');
	},false); // 버블링
    
},false); // 버블링
<body>
	<h1 id="header">클릭</h1>
</body>