728x90
자바스크립트 이벤트
웹 페이지에서 발생하는 사용자 동작 또는 웹 페이지의 상태 변화와 같은 다양한 상황에 대한 반응을 정의하는 매커니즘
주로 웹 페이지의 동적 상호 작용을 구현하거나 사용자와 웹 어플리케이션 간의 상호 작용을 처리하기 위해 사용됨
이벤트 종류
이벤트 핸들러
이벤트를 처리하기 위해 이벤트 핸들러(또는 이벤트 리스너)라고 하는 함수
이벤트 핸들러는 이벤트가 발생했을 때 실행됨
이벤트 등록
이벤트 핸들러를 이벤트 대상(HTML 요소)에 등록함
이벤트 대상은 보통 DOM(문서 객체 모델)을 통해 선택됨
const button = document.getElementById('myButton');
button.addEventListener('click', myFunction);
이벤트 객체
이벤트 핸들러 함수는 이벤트 객체를 받음
이 객체에는 이벤트에 대한 정보(예: 클릭 위치, 키 코드)가 포함되어 있음
이벤트 전파
이벤트는 일반적으로 상위 요소에서 하위 요소로 전파됨
이를 이용하여 이벤트 버블링과 캡처링 단계에서 이벤트를 캐치하거나 중단할 수 있음
이벤트 제거
이벤트 핸들러를 등록한 후, 이벤트를 더 이상 필요하지 않을 때 제거할 수 있음
removeEventListener 메서드를 사용하여 이벤트 핸들러를 제거할 수 있음
button.removeEventListener('click', myFunction);
기본 동작의 중단
이벤트 핸들러 내에서 preventDefault() 메서드를 호출하여 기본 동작(예: 링크 클릭 시 페이지 이동)을 중단할 수 있습니다.
link.addEventListener('click', function (event) {
event.preventDefault();
});
이벤트 위임
이벤트 위임은 상위 요소에 하나의 이벤트 핸들러를 등록하고, 하위 요소에서 발생하는 이벤트를 상위 요소에서 처리하는 패턴
이로써 동적으로 생성되는 요소에도 이벤트를 적용할 수 있음
실습1 : 키보드 입력 이벤트
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>키보드 입력 이벤트</title>
<style type="text/css">
input {
border: 5px solid black;
}
</style>
</head>
<body>
<input type="text" onkeydown="test(event)" placeholder="keydown 이벤트">
<script type="text/javascript">
function test(event){
console.log(event.keyCode);
if (event.keyCode == 13) {
console.log(event.target); // Thread
alert(event.target.value); // 브라우저에서 alert 먼저 띄우고 -> console.log 찍힘
}
}
</script>
</body>
</html>
실습2 : 마우스 입력 이벤트
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>마우스 입력 이벤트</title>
<style type="text/css">
#box {
width: 50px;
height: 50px;
background-color: lightgray;
cursor: pointer;
}
</style>
</head>
<body>
<div id="box" onmouseover="test1(this)" onmousedown="test2(this)" onmouseout="test3(this)"></div>
<script type="text/javascript">
function test1(obj) {
obj.style.backgroundColor = 'lightgreen';
}
function test2(obj) {
obj.style.backgroundColor = 'lightpink';
}
function test3(obj) {
obj.style.backgroundColor = 'lightblue';
}
</script>
</body>
</html>
실습 3 : 속성 값에 따른 이벤트
- 1번째 목록
- 2번째 목록
- 3번째 목록
- 4번째 목록
- 5번째 목록
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<button type="button" onclick="test()">id속성값이 check인 목록에 변화주기</button>
<br><br>
<button type="button" onclick="test2()">class속성값이 check2인 목록에 변화주기</button>
<ul>
<li class="check2">1번째 목록</li>
<li id="check">2번째 목록</li>
<li class="check2">3번째 목록</li>
<li>4번째 목록</li>
<li class="check2">5번째 목록</li>
</ul>
<script type="text/javascript">
function test() {
var obj = document.getElementById('check');
obj.style.backgroundColor = 'blue';
}
function test2() {
var arr = document.getElementsByClassName('check2');
for (var i = 0; i < arr.length; i++) {
arr[i].style.backgroundColor = 'gray';
}
}
</script>
</body>
</html>
실습 4 : 이벤트 리스너 등록
- 1번째 목록
- 2번째 목록
- 3번째 목록
- 4번째 목록
- 5번째 목록
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
li {
margin: 10px;
cursor: pointer;
border: 1px solid black;
}
.click {
/* 클릭 이벤트를 통해
클래스명이 click이 된 요소가 있다면, */
background-color: lightpink !important;
}
</style>
</head>
<body>
<ul>
<li>1번째 목록</li>
<li>2번째 목록</li>
<li>3번째 목록</li>
<li>4번째 목록</li>
<li>5번째 목록</li>
</ul>
<script type="text/javascript">
var arr = document.querySelectorAll('li');
// 이벤트를 연결할때에
// 이벤트 리스너를 등록하는 방식으로 적용할 수 있다!
for (var i = 0; i < arr.length; i++) {
// arr[i].addEventListener('이벤트명', '함수명');
arr[i].addEventListener('mouseover', function(){
this.style.backgroundColor = 'lightgray';
});
arr[i].addEventListener('mouseout', function(){
this.style.backgroundColor = 'white';
});
// 함수를 바로 연결하는 방식
// 일반적으로, 사전에 등록해둔 CSS와 연결되게끔 코드를 작성하는편
arr[i].onclick = test;
}
function test() {
if (this.className == 'click') {
this.className = '';
}
else {
this.className = 'click';
}
}
</script>
</body>
</html>
728x90
'Web > Javascript' 카테고리의 다른 글
[Javascript] AJAX 와 JSON (0) | 2023.06.29 |
---|---|
[Javascript] jQuery 라이브러리 (0) | 2023.06.29 |
[Javascript] 주사위 게임 실습 (0) | 2023.06.25 |
[Javascript] 가위바위보 실습 (0) | 2023.06.25 |
[Javascript] 자바스크립트 (0) | 2023.06.24 |