분석가 황규진 2024. 7. 10. 14:15

이벤트

  • 웹 브라우저에서 사용자가 화면을 클릭하는 사건, 사용자가 키보드를 누르는 사건과 같은 다양한 사건이 발생, 이러한 사건을 이벤트(event)라고 함.

이벤트의 종류

  • 이벤트는 애플리케이션 사용자가 발생시킬 수도 있고 애플리케이션이 스스로 발생 시킬 수도 있음
    • 마우스 이벤트
    • 키보드 이벤트
    • HTML 프레임 이벤트
    • HTML 입력 양식 이벤트
    • 유저 인터페이스 이벤트
    • 구조 변화 이벤트
    • 터치 이벤트
  • 이벤트 모델
    • 이벤트를 연결하는 방법을 ‘이벤트 모델(event model)’이라고 함
    • (현재)이벤트 표준 모델
      • addEventListener( )

 

이벤트 관련 용어 정리

  • 아래 코드와 같이, window 객체의 onload (이벤트) 속성에 함수(자료형)를 할당하는 것을 “이벤트를 연결한다”라고 함
<script>
	window.onload = function(){
	}
</script>
  • window가 웹 페이지를 로드 (완료)했을 때(사건 발생되었을 때) 실행되는 함수
  • ‘load’를 이벤트 이름 또는 이벤트 타입(Event Type)이라 하고
  • ‘onload’를 이벤트 속성이라고 함
  • 이벤트 속성에 할당한 함수를 이벤트 리스너(Event Listener) 또는 이벤트 핸들러(Event Handler)라고 함.

 

아래 코드에서 이벤트 이름, 이벤트 속성, 이벤트 리스너를 찾아보시오.

<script>
	window.onload = function(){
		let header = document.getElementById('header')
		function doItWhenClick() { alert('Click!') }
		header.onclick = doItWhenClick
	}
</script>
<body>
	<h1 id="header">여기 클릭</h1>
</body>
  • windows 객체에 대해, 위에서 설명과 동일하며
  • header 객체의 이벤트 이름은 click, 이벤트 속성은 onclick, 이벤트 리스너는 whenClick( ) 함수
  • 문서 객체에 이벤트를 연결하는 방법을 이벤트 모델이라고 함
  • DOM Level 단계 별 이벤트 모델
    • DOM Level 0
      • 인라인 이벤트 모델
      • 기본 이벤트 모델
    • DOM Level 1
      • 마이크로소프트 인터넷 익스플로러 이벤트 모델
      • 표준 이벤트 모델

 

고전 이벤트 모델

  • 고전 이벤트 모델은 자바스크립트에서 문서 객체의 “이벤트 속성”에 이벤트를 연결하는 방법
    • 이름은 ‘고전’이지만 현재에도 많이 사용됨.

이벤트 연결

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script>
		window.onload = function(){
			let header = document.getElementById('header')
			function doItWhenClick() { alert('Click!') }
			header.onclick = doItWhenClick
		}
	</script>
</head>
<body>
	<h1 id="header">여기 클릭</h1>
</body>
</html>

  • 고전 이벤트 모델은 이벤트 하나에 이벤트 리스너를 하나만 연결할 수 있음
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script>
		window.onload = function(){
			let header = document.getElementById('header')
			header.onclick = function() { alert('Click!') }

			let id123 = document.getElementById('id123')
			id123.onclick = function() { 
				id123.innerHTML = 'There'
			}
		}
	</script>
</head>
<body>
	<h1 id="header">Click</h1>
	<h5 id="id123">Here</h5>
</body>
</html>

이벤트 해제

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script>
		window.onload = function(){
			let header = document.getElementById('header')
			header.onclick = function() {
				alert('Click!')
				header.onclick = null
			}
		}
	</script>
</head>
<body>
	<h1 id="header">여기 클릭</h1>
</body>
</html>

한번 클릭 한 후에 onclick을 null로 만들어서 다시 클릭하면 아무 변화가 없음

  • 3번 클릭한 후 해제
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script>
		window.onload = function(){
			var i = 0
			let header = document.getElementById('header')
			header.onclick = function() {
				alert('Click!')
				i++
				if (i==3){
					header.onclick = null
				}
			}
		}
	</script>
</head>
<body>
	<h1 id="header">여기 클릭</h1>
</body>
</html>

 

 

Quiz

A를 클릭하면 → B로 변경, B를 클릭하면 → A로 변경 되도록 하는 코드 작성

<!DOCTYPE html>
<html>
<head> <title>Index</title>
<script>
	window.onload = function() {
		var doc = document.getElementById(‘id_a’);
		doc.onclick = function( ) {
			if ( doc.innerHTML == ‘A’ ) {
					doc.innerHTML = ‘B’;
			} else {
					doc.innerHTML = ‘A’;
				}
			};
		};
	</script>
</head>
<body>
<h1 id = ‘id_a’> A </h1>
</body>
</html>
  • Id가 ‘id_1’인 <h1> 태그를 클릭하면 id가 ‘id_2’인 <h1> 태그의 텍스트가 Here로 바뀌고
  • Id가 ‘id_2’인 <h1> 태그를 클릭하면 id가 ‘id_1’인 <h1> 태그의 텍스트가 There로 바뀌고
  • Id가 ‘back’인 <h1> 태그를 클릭하면 … 원래대로
<script>
	window.onload = function() {
		var id1 = document.getElementById(‘id_1’);
		var id2 = document.getElementById(‘id_2’);
		var idback = document.getElementById(‘back’);
		id1.onclick = function( ) { id2.innerHTML = ‘Here’; };
		id2.onclick = function( ) { id1.innerHTML = ‘There’;};
		idback.onclick = function( ) {
			id1.innerrHTML = ‘Here’;
			id2.innerHTML = ‘There’;
		};
		};
	</script>
<body>
	<h1 id = ‘id_1’> Here </h1>
	<h1 id = ‘id_2’> There </h1>
	<h1 id = ‘back’> Back </h1>
</body>

버튼 A 클릭시 숫자 증가

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script>
		document.addEventListener('DOMContentLoaded', function(){
			let buttonA = document.getElementById('button-a')
			let counterA = document.getElementById('counter-a')
			buttonA.onclick = function(){
				counterA.innerHTML = Number(counterA.textContent) + 1
			}
		})
	</script>
</head>
<body>
	<button id="button-a">Button A</button>
	<h1>Button A - <span id = 'counter-a'>0</span></h1>
</body>
</html>

버튼 A 클릭시 숫자 증가, 버튼 B 클릭시 A,B 둘다 증가

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script>
		document.addEventListener('DOMContentLoaded', function(){
			let buttonA = document.getElementById('button-a')
			let counterA = document.getElementById('counter-a')
			let buttonB = document.getElementById('button-b')
			let counterB = document.getElementById('counter-b')
			buttonA.onclick = function(){
				counterA.innerHTML = Number(counterA.textContent) + 1
			}
			buttonB.onclick = function(){
				counterA.innerHTML = Number(counterA.textContent) + 1
				counterB.innerHTML = Number(counterB.textContent) + 1
			}

		})
	</script>
</head>
<body>
	<button id="button-a">Button A</button>
	<h1>Button A - <span id = 'counter-a'>0</span></h1>
	<button id="button-b">Button B</button>
	<h1>Button B - <span id = 'counter-b'>0</span></h1>
</body>
</html>

 

이벤트 강제 실행

  1. 왜 강제로 이벤트를 실행시키나? 이벤트를 강제로 발생 시키는 기법은 자주 사용되지 않지만 특정 상황에서 활용하면 코드의 길이를 대폭 줄일 수 있음

이벤트 핸들러를 강제로 실행 시키는 방법

header.onclik( )
<!DOCTYPE html>
<html>
<head> <title></title> 
	<script>
		window.onload = function( ) {
		var buttonA = document.getElementById(‘button-a’);
		var buttonB = document.getElementById(‘button-b’);
		var counterA = document.getElementById(‘counter-a’);
		var counterB = document.getElementById(‘counter-b’);
		buttonA.onclick = function( ) { counterA.innerHTML = Number(counterA.innerHTML) + 1; };
		buttonB.onclick = function( ) { 
				buttonA.onclick( );
				counterB.innerHTML = Number(counterB.innerHTML) + 1;
			};
		};
	</script>
</head>
<body>
	<button id = ‘button-a’> ButtonA </button>
	<button id = ‘button-b’> ButtonB </button>
	<h1>Button A - <span id=‘counter-a’>0</span></h1>
	<h1>Button B - <span id=‘counter-b’>0</span></h1>
</body>

 

 

인라인 이벤트 모델

  • 인라인 이벤트 모델은 HTML 페이지의 가장 기본적인 이벤트 연결 방법
    • 2000년 이전에는 ‘인라인 이벤트 모델’을 많이 사용, 이후 ‘고전 이벤트 모델’을 주로 사용, 이후 표준 이벤트 모델 등장
    • 현재는 인라인 이벤트 모델과 표준 이벤트 모델을 주로 사용
<body>
	<h1 onclick = ‘’>Click</h1>
</body>
<body>
	<h1 onclick = “alert(’클릭’)”>Click</h1>
</body>

<body>
	<h1 onclick = “var num = 73; alert(num)”>Click</h1>
</body>

<!DOCTYPE html>
<html>
<head> <title></title> 
	<script>
		function whenClick( event ) {
			alert(‘클릭’);
		}
	</script>
</head>
<body>
	<h1 onclick=“whenClick(event)”>Click</h1>
</body>
</html>

 

 

키보드 이벤트

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script>
		document.addEventListener('DOMContentLoaded', () =>{
			const textarea = document.querySelector('textarea')
			const h1 = document.querySelector('h1')
			textarea.addEventListener('keyup', (event)=>{
				const length = textarea.value.length
				h1.textContent = `글자 수 : ${length}`
			})
		})
	</script>
</head>
<body>
	<h1></h1>
	<textarea></textarea>
</body>
</html>

글자 수 10 자 이상 입력하면 alert하고 10자로 돌아가서 보여주기

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script>
		document.addEventListener('DOMContentLoaded', () =>{
			const textarea = document.querySelector('textarea')
			const h1 = document.querySelector('h1')
			textarea.addEventListener('keyup', (event)=>{
				const length = textarea.value.length
				h1.textContent = `글자 수 : ${length}`
				if (length > 10){
					alert('10자 제한')
					textarea.value = textarea.value.substring(0,10)
					h1.textContent = '글자 수 : 10'
				} 
			})
		})
	</script>
</head>
<body>
	<h1></h1>
	<textarea></textarea>
</body>
</html>

 

키보드 이벤트가 발생 했을 때 이벤트 객체

  • 어떤 키가 눌렸는지
  • 관련된 속성을 가지고 있음

<script>
	document.addEventListener('DOMContentLoaded', ()=>{
		const h1 = document.querySelector('h1')
		const print = (event)=>{
			let output =''
			output += `alt:${event.altKey}<br>`
			output += `ctrl:${event.ctrlKey}<br>`
			output += `shift:${event.shiftKey}<br>`
			output += `code:${typeof(event.code) != 'undefined' ?
										event.code:event.keyCode}<br>`
			h1.innerHTML = output
	} 
		document.addEventListener('keydown', print)
		document.addEventListener('keyup', print)
	})
</script>
<body>
	<h1></h1>
</body>

event.code가 있으면

event.code를 출력하고

undefined라면

event.keyCode를 출력

 

글자 입력 양식 이벤트

  • 사용자로부터 어떠한 입력을 받을 때 사용하는 요소를 “입력 양식(form)”이라고 함
    • 예, input, textarea, button, select 태그 등
<script>
	document.addEventListener('DOMContentLoaded', ()=>{
		const input = document.querySelector('input')
		const button = document.querySelector('button')
		const p = document.querySelector('p')
		button.addEventListener('click', ()=>{
			const inch = Number(input.value)
			if(isNaN(inch)) {
				p.textContent = '숫자를 입력하세요'
				return
			}
			const cm = inch * 2.54
			p.textContent = `${cm}[cm]`
		})
	})
</script>
<body>
	<input type="text">inch<br>
	<button>계산</button>
	<p></p>
</body>

 

이벤트 발생 객체와 이벤트 객체

  • 사건(이벤트)가 발생하면 ‘누가, 언제, 어디서, 무엇을, 어떻게, 왜’를 정의할 수 있듯, 자바스크립트도 이벤트 객체를 사용하면'누가, 언제, 어디서, 무엇을, 어떻게, 왜’를 정의 할 수 있음.
    • “이벤트를 누가 발생시켰을까?”라는 물음은 이벤트 리스너 안에서 this 키워드를 사용하여 이벤트 발생 객체를 찾을 수 있음
<!DOCTYPE html>
<html>
<head>
<title></title>
	<script>
		document.addEventListener('DOMContentLoaded', function(){
			document.getElementById('header').onclick = function(){
				alert( this )
			}
			document.getElementById('button_id').onclick = function(){
				alert(this)
			}
			document.getElementById('div_id').onclick = function(){
				alert(this)
			}
		})
	</script>
</head>
<body>
	<h1 id="header">Click</h1>
	<button id = "button_id">버튼</button>
	<div id = "div_id">Hello World!</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
	document.addEventListener('DOMContentLoaded', function(){
		document.getElementById('header').onclick = function(e){
			let event = e || window.event
			document.body.innerHTML = ''
			for(var key in event) {
				document.body.innerHTML += `<p>${key} : ` + event[key] + '</p>'
			}
		} 
	})
</script>
</head>
<body>
<h1 id="header">Click</h1>
</body>
</html>