▶ 마우스 이벤트
이벤트 | 설명 |
click | 마우스를 클릭했을 때 이벤트가 발생 |
dbclick | 마우스를 더블클릭했을 때 이벤트가 발생 |
mouseover | 마우스를 오버했을 때 이벤트가 발생 |
mouseout | 마우스를 아웃했을 때 이벤트가 발생 |
mousedown | 마우스를 눌렀을 때 이벤트가 발생 |
mouseup | 마우스를 떼었을 때 이벤트가 발생 |
mousemove | 마우스를 움직였을 때 이벤트가 발생 |
▶ 키 이벤트
이벤트 | 설명 |
keydown | 키를 눌렀을 때 이벤트가 발생 |
keyup | 키를 떼었을 때 이벤트가 발생 |
keypress | 키를 누른 상태에서 이벤트가 발생 |
▶ 폼 이벤트
이벤트 | 설명 |
focus | 포커스가 이동되었을 때 이벤트가 발생 |
blur | 포커스가 벗어났을 때 이벤트가 발생 |
change | 값이 변경되었을 때 이벤트가 발생 |
submit | submit 버튼을 눌렀을 때 이벤트가 발생 |
reset | reset 버튼을 눌렀을 때 이벤트가 발생 |
select | input이나 textarea 요소 안의 텍스트를 드래그하여 선택했을 때 이벤트가 발생 |
▶ 로드, 기타 이벤트
이벤트 | 설명 |
load | 로딩이 완료되었을 때 이벤트가 발생 |
abort | 이미지의 로딩이 중단되었을 때 이벤트가 발생 |
resize | 사이즈가 변경되었을 때 이벤트가 발생 |
scroll | 스크롤바를 움직였을 때 이벤트가 발생 |
▶ 이벤트 연결
- 이벤트를 연결하는 방식에는 인라인 이벤트 모델, 기본 이벤트 모델, 표준 이벤트 모델이 있으며 이벤트 앞에 'on'을 붙임
▶ 인라인 이벤트 모델
인라인 이벤트 모델은 html 요소에 직접 이벤트를 연결하는 방식
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script> function sum(n) {
alert(n);
}
</script> </head>
<body>
<button onclick='sum(10);'>클릭</button>
</body>
</html>
|
▶ 기본 이벤트 모델
HTML 요소를 취득한 후 이벤트를 '객체의 메서드' 형식(객체.메서드 = function( ){ ... }) 으로 연결하는 방식
HTML 요소를 취득 할 /대는 순서상 '취득할 요소'가 '요소 취득 명령어' 이전에 있어야 함
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script> // 기본 이벤트 모델
let bt = document.getElementById('bt'); //요소 취득 명령어
bt.onclick = function() {
console.log('ok'); // ok
}
</script> </head>
<body>
<button id="bt">클릭</button> <!-- 취득할 요소 -->
</body>
</html>
|
'취득할 요소'가 '요소 취득 명령어' 이후에 오면 반드시 load 이벤트를 적용
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script> window.onload = function() {
let bt = document.getElementById('bt');
bt.onclick = function() {
console.log('ok');
};
};
</script> </head>
<body>
<button id="bt">클릭</button> <!-- 취득할 요소 -->
</body>
</html>
|
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script> window.onload = function() {
let bt = document.getElementById('bt');
function view() {
console.log('view');
};
bt.onclick = view;
};
</script> </head>
<body>
<button id="bt">클릭</button> <!-- 취득할 요소 -->
</body>
</html>
|
기본 이벤트 모델로 다른 함수를 호출 때는 함수에 ( )를 붙이지 않음
만약 ( )를 붙이게 되면 웹페이지가 실행되었을 때 요소를 클릭하지 않아도 이벤트가 한번 실행되게 됨
이것을 이벤트 강제 실행이라고 함
bt.onclick = view( ) |
▶ 표준 이벤트 모델
표준 이벤트 모델은 객체.addEventListener('이벤트', 함수)의 방식으로 이벤트 연결
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script> // 표준 이벤트 모델
window.onload = function( ) {
let bt = document.getElementById('bt');
function view() {
console.log('ok');
}
bt.addEventListener('click',view);
}
</script> </head>
<body>
<button id="bt">클릭</button> <!-- 취득할 요소 -->
</body>
</html>
|
'기본 이벤트 모델'은 객체에 동일한 이벤트가 한번만 적용되는 반면,
'표준 이벤트 모델'은 여러번 적용이 가능
<script> window.onload = function( ) { console.log('ok1'); // ok1은 실행하지 않음 }; window.onload = function( ) { console.log('ok2'); // ok2 }; </script> |
<script> function win1( ) { console.log('ok1'); } function win2( ) { console.log('ok2') }; addEventListener('load', win1); // ok1 addEventListener('load', win2); // ok2 </script> |
▶ 이벤트 객체
내장 객체처럼 자바스크립트에서 기본적으로 제공해 주는 객체
이벤트 객체를 이용하면 마우스를 클릭했을 때 클릭한 좌표 값이라든지 이벤트를 발생시킨 객체가 어떤 것인지 등에 대한 정보 값을 쉽게 얻을 수 있다
bt.onclick = function(event) { event.프로퍼티 event. 메서드 } |
익명 함수으이 매개 변수 event가 이벤트 객체를 의미
변수명을 반드시 'event'로 사용할 필요는 없으나, 보통 이벤트 객체의 의미로 'event'를 많이 사용
▶ 이벤트 객체 주요 프로퍼티
프로퍼티 | 설명 |
target | 이벤트를 발생시킨 객체를 반환 |
type | 이벤트의 이름을 반환 |
clientX | 이벤트가 발생한 x좌표 값을 반환(브라우저 기준) |
clientY | 이벤트가 발생한 y좌표 값을 반환(브라우저 기준) |
screenX | 이벤트가 발생한 x좌표 값을 반환(모니터기준) |
screenY | 이벤트가 발생한 y좌표 값을 반환(모니터기준) |
button | 마우스 왼쪽(0), 가운데(1), 오른쪽(2) 버튼 값을 반환 |
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
div{
height: 100px;
background: #718c00;
margin-top: 20px;
color: #fff;
}
</style>
</head>
<body>
<button id="bt">클릭</button> <!-- 취득할 요소 -->
<div id="area">여기에 마우스 왼쪽, 가운데, 오른쪽 버튼 클릭</div>
<script src="index3.js"></script>
</body>
</html>
|
window.onload = function() {
let bt = document.getElementById('bt');
let area= document.getElementById('area');
bt.onclick = function(event) {
console.log(event.target);
console.log(event.type);
console.log(event.clientX);
console.log(event.clientY);
console.log(event.screenX);
console.log(event.screenY);
}
area.onmousedown = function(event) {
console.log(event.button);
};
};
|
▶ 이벤트 객체 주요 메서드
메서드 | 설명 |
preventDefault( ) | 기본 이벤트의 실행을 막아 줍니다. |
stopPropagation( ) | 이벤트 버블링 방지해 줌 |
** preventDefault( ) 메서드
기본 이벤트 (Default event)는 html 요소 중 자바스크립트의 이벤트가 아닌, html 요소 자체가 가지고 있는 이벤트
예를들어,
<a> 요소는 내용을 클릭했을 때 링크 주소로 페이지가 이동하거나 <submit> 버튼처럼 버튼을 클릭했을 때 폼 값을 전송하는 요소 자체의 이벤트를 말함
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<script src="index3.js"></script>
</body>
</html>
|
window.onload = function() {
let icox = document.getElementById('icox');
icox.onclick = function() {
alert('아이콕스');
}
}
|
아이콕스를 클릭하면 alert( ) 함수가 실행되고 <a> 태그에 연결된 주소로 이동
<a> 태그의 기본 이벤트를 발생 시키지 않으려면 preventDefault( ) 메서드를 사용하면 됨
icox.onclick = function() {
alert('아이콕스');
event.preventDefault( ) }
|
event.preventDefault( ) 대신return false를 사용해도 기본 이벤트가 발생하지 않음
icox.onclick = function() { alert('아이콕스');
return false; }
|
stopPropagation( ) 메서드
'이벤트 버블링'은 부모 요소와 자식 요소 모두에 이벤트가 연결되어 있을 경우 자식 요소의 이벤트를 실행 하였을 때
부모 요소의 이벤트도 같이 실행되는 현상을 말함
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
*{
padding: 0;
margin: .0;
}
#outer{
background: #ff0000;
padding: 20px;
}
#inner{
background: #00ff00;
padding: 20px;
}
</style>
</head>
<body>
<div id="outer">
<p id="inner">클릭</p>
</div>
<script src="index3.js"></script>
</body>
</html>
|
window.onload = function() {
let outer= document.getElementById('outer');
let inner= document.getElementById('inner');
outer.onclick = function() {
alert('부모 이벤트');
};
inner.onclick = function() {
alert('자식이벤트');
};
}
|
inner영역을 클릭하면 자신의 이벤트 실행 후 부모의 이벤트도 실행되는 현상을 볼 수 있음
이런 이벤트 버블링 현상을 방지하려면 stopPropagation( ) 메서드를 사용하면 됨
inner.onclick = function() {
alert('자식이벤트');
event.stopPropagation( ); };
|
추가된 코드의 결과를 확인해 보면 부모 이벤트가 발생하되지 않는 것을 확인할 수 있다.