본문 바로가기
Javascript/GMA(2302~)

23.04.17 자바스크립트 이벤트 -1

by hyerin1201 2023. 4. 17.

1. 이벤트란?

 
  이벤트란? : 브라우저 안에서 사용자가 실행하는 모든 동작!
   1. 문서로딩 이벤트 : 특정 문서를 불러올때 사용하는 이벤트(ex. 문서를 모두 불러온 이후에 어떤 함수를 실행)
   2. 마우스 이벤트 : 클릭, 더블클릭, 포인터가 특정 요소 위에 올라갔을때, 벗어났을 , 포커스, 블러 처리
   3. 키보드 이벤트 : 키를 눌렀을때, 키에서 손을 땔때, 키를 누르고 있는 동안
   4. 이벤트 : 폼태그 안에서 특정 요소에 포커스가 갔을때, 블러, 목록, 체크상태 변경
 
   "on"이라는 키워드 + 이벤트명 : 이벤트 핸들러!
   이벤트 핸들러 : 이벤트가 발생하면, 이벤트에 맞는 연결동작이 필요, 이벤트 연결동작을 처리하는 .
 

 

2. 문서 로딩 이벤트

   
   window.onload = alert("안녕하세요");
   document의 상위개념인 window가 alert에 관여하기 때문에. : 윈도우 브라우저를 로드에서가져온다음. 경고창을 띄운다.
   onload : 특정한 문서에 로딩이 끝났을때 어떠한 결과를 보여주는 이벤트.
 

 

3. 마우스 클릭 이벤트

 
   마우스 클릭 이벤트
   const button = document.querySelector("button");
 
   button.onclick = () => {
   document.body.style.backgroundColor = "green";
   }
 

 

4. 키보드 이벤트 예제

 
   키보드 이벤트 *문서객체 > body 태그에 들어가는 요소의 영향을 받는다
 
   1. 어떤 키를 눌렀을때, 해당 키를 출력할 공간.
   2. 어떤 키를 눌렀는 지에 대한 정의 .
 
   const body = document.body;  // 키보드이벤트는 바디태그의 영향을 받는다.
   const result = document.querySelector("#result"); 

   body.addEventListener("keydown", (event) => { //어떤값이 들어갈지 모를때 매개변수를 입력(임시변수), 안넣는 경우는 안넣어도 함수가 돌아가는 경우
   result.innerText = `code: ${event.code}, key: ${event.key}` ;
   });
 

 

5. 자바스크립트 이벤트를 작동시키는 2가지 방법

 
   자바스크립트 이벤트를 작동시키는 2가지 방법
 
   1. HTML 태그에 직접 함수를 연결한다. <태그 이벤트핸들러 = "함수명"> *간단한 함수 또는 내장함수 일때. 권장하진 않음
   => 문제점 : 복수의 이벤트를 적용하고 싶을때 사용하지 못한다, 사용자가 정의한 함수를 활용해서 html에 함수를 연결한 경우에
                      자바스크립트에서 함수명 이 변경된다면 html에서도 변경 시켜줘야하는 번거로움이 있다.
 
   2. 자바스크립트에서 직접 함수 연결 선택요소(*이벤트를 주고싶은 요소).on이벤트 = 함수
 

5-1.

 
   => 함수를 사전에 정의하는 방법도 있다.
   function changeBg() {
   document.body.style .backgroundColor = "green"  //함수사전 정의
   }
   const button = document.querySelector("button");
   button.onclick = changeBg; // 클릭되었을때 함수실행
 

 

6. addEventListener 의 사용

 
   addEventListener : 복수의 이벤트를 적용할 있다! (html에 직접 이벤트를 준것과 중복가능.)
   더 확장성이 있으므로 이벤트 핸들러보다 많이 사용된다.
 
   선택요소.addEventListener(이벤트명, 함수)
 
   const button = document.querySelector("button")
   function changeBackground() {
   document.body.style.backgroundColor = "green";
   }
   button.addEventListener("click", changeBackground);
 

 

7. 글자를 인풋 박스에 입력하면 글자수를 확인해주는 코드를 짜보자!

 
   글자수 확인 버튼 만들기
   1. 인풋 박스 안에 입력된 텍스트 알기
   2. 해당 텍스트의 갯수를 알기.
   3. 갯수 숫자만큼 출력.
 

Javascript

const button = document.querySelector("#btn");
const result = document.querySelector("#result");

button.addEventListener("click", () => {
  const word = document.querySelector("#word");
  let count = word.value.length; //갯수는 길지 짧을지 몇개일지 모르므로 let
  result.innerText = `${count}`;
});

 

CSS

* {
  margin: 0;
  padding: 0;
}
body {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
button {
  padding: 5px 10px;
  cursor: pointer;
}
#result {
  text-align: center;
  font-weight: bold;
  font-size: 1.5em;
  margin-top: 30px;
  color: crimson;
}

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">
  <script defer src="/script_1.js"></script>
  <link rel="stylesheet" href="/style_1.css">
  <title>Document</title>
</head>
<body>
  <div class="" id="contents">
    <input type="text" id="word">
    <button id="btn">글자수 확인</button>
  </div>
  <div id="result"></div>
</body>
</html>

 

결과 화면