Learn & Record

HTML CSS JS (이벤트 설정, 이벤트 해제, 키보드 이벤트, 키보드 버튼 이벤트, 별 프로그램, form 태그 이벤트) 본문

Dev/HTML CSS JS

HTML CSS JS (이벤트 설정, 이벤트 해제, 키보드 이벤트, 키보드 버튼 이벤트, 별 프로그램, form 태그 이벤트)

Walker_ 2024. 4. 3. 12:44

1. 이벤트 설정하기

 - 이벤트 event : 모든 문서 객체는 생성되거나, 클릭되거나, 마우스를 위에 올리거나 할 때 발생.

 - 이벤트가 발생할 때 실행할 함수는 addEventListener()메소드를 사용해서 콜백 함수로 등록

 

 - 문서객체.addEventListener(이벤트 이름, 콜백 함수);

 

 - 이벤트가 발생할 때 실행할 함수(콜백 함수)를 이벤트 리스너 event Listener 또는 이벤트 핸들러 event handler 라고 함

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /*

         */
        document.addEventListener('DOMContentLoaded', () => {
            const h1 = document.querySelector('h1');
            let counter = 0;

            h1.addEventListener('click', function(event) { // h1태그에 click 이벤트가 발생할 때 실행할 함수
                counter++;
                h1.textContent = `클릭 횟수 : ${counter}`
            });
        });
    </script>
    <style>
        h1 {
            /* 클릭 여러 번 할때, 글자가 선택되는 것을 막기 위한 스타일. 드래그 안됨 */
            user-select: none;
            cursor: pointer;
            background-color: #00bbdd;
        }
    </style>
</head>
<body>
    <h1>클릭 횟수 : 0</h1>
</body>
</html>

 

2. 이벤트 해제하기

 - 이벤트를 제거할 때는 removeEventListener() 메소드를 사용

 - 문서 객체.removeEventListener(이벤트 이름, 이벤트 리스너);

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const h1 = document.querySelector('h1');
      const conBtn = document.querySelector('#connect');
      const disConBtn = document.querySelector('#disconnect');
      const p = document.querySelector('p')
      let count = 0;
      let isConnect = false; // 이벤트를 여러 번 연결되지 않게

      const listener = (event) => { // 이벤트를 제거하려면 이벤트 리스너를 변수 또는 상수로 가지고 있어야 함
        h1.textContent = `클릭 횟수 : ${count++}`; // h1 태그 안에 클릭마다 텍스트 변경
      }

      conBtn.addEventListener('click', function() { // 이벤트 연결하는 이벤트 리스너
        if (isConnect === false) {
          h1.addEventListener('click', listener); // h1 클릭 시 listener 함수 발생
          p.textContent = `이벤트 연결 상태: 연결` // p의 텍스트를 변환
          conBtn.style.display = 'none' // 이벤트 연결 버튼 숨김
          disConBtn.style.display = '' // 해제 버튼 디스플레이 기본 값
          isConnect = true;
        }
      })
      disConBtn.addEventListener('click', function (){
        if (isConnect === true) {
          h1.removeEventListener('click', listener); // h1의 listener 함수 제거
          p.textContent = `이벤트 연결 상태: 해제` // p의 텍스를 변환
          conBtn.style.display = '' // 연결 버튼 디스플레이 기본값
          disConBtn.style.display = 'none' // 해제 버튼 디스플레이 none 값
          isConnect = false;
        }
      })
    })
  </script>
  <style>
    h1 {
      /* 클릭 여러 번 할때, 글자가 선택되는 것을 막기 위한 스타일. 드래그 안됨 */
      user-select: none;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <h1>클릭 횟수 : 0</h1>
  <button id="connect">이벤트 연결</button>
  <button id="disconnect">이벤트 제거</button>
  <p>이벤트 연결 상태: 해제</p>
</body>
</html>

 

3. 키보드 이벤트

 - keydown : 키가 눌릴 때 실행. 키보드를 꾹 누르고 있을 때도, 입력될 때도 실행

 - keypress : 키가 입력되었으 때 실행. 웹 브라우저에 따라서 아시아권의 문자를 제대로 처리 못하는 문제가 있음

 - keyup : 키보드에서 키가 떨어질 때 실행

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // 남은 글자 수 출력하기
        document.addEventListener('DOMContentLoaded', ()=> {
            const h1 = document.querySelector('h1')
            const textArea = document.querySelector('textarea')
            let count = 0

            textArea.addEventListener('keyup', function () { // 키보드에서 키가 떨어질 때 실행
                // console.log(textArea.textLength) // 글자 수 로그 출력
                // h1.textContent = `글자 수 : ${textArea.textLength}`; // 글자 수에 따라 h1 텍스에 기입

                console.log(textArea.value.length);
                // value 속성으로 입력양식(form 태그)의 글자(문자열)를 읽을 수 있음
                const length = textArea.value.length;
                h1.textContent = `글자 수 : ${textArea.value.length}`; // 글자 수에 따라 h1 텍스에 기입
            });
            textArea.focus();
        })
    </script>
</head>
<body>
    <h1>글자 수 : 0</h1>
    <textarea></textarea>
</body>
</html>

 

4. 키보드 이벤트와 관련된 이벤트 속성

 - code : 입력한 키

 - keyCode : 입력한 키를 나타내는 숫자

 - altKey : alt 키를 눌렀는지

 - ctrlKey : ctrl 키를 눌렀는지

 - shiftKey : shift 키를 눌렀는지

 

 - code 속성은 입력한 키를 나타내는 문자열이 들어있고

 - altKey, ctrlKey, shiftKey 속성은 해당 키를 눌렀는지 불 자료형이 들어 있음

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <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>`
                // event.code가 있으면 event.code를 출력하고, undefined라면 event.keyCode를 출력
                output += `code: ${typeof(event.code) !== 'undefined' ? event.code : event.keyCode}<br>`

                h1.innerHTML = output;
            }
            document.addEventListener('keydown', print); // 키가 눌릴 때 출력
            document.addEventListener('keyup', print); // 키가 떨어질 때 출력
        })
    </script>
</head>
<body>
    <h1></h1>
</body>
</html>

 

5. keyCode 속성 활용

/*
* keyCode 속성 활용
* keyCode 속성은 입력한 키를 숫자로 나타냄. 37 38 39 40이 방향키 왼쪽, 위, 오른쪽, 아래를 나타냄
 */
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /*
        * keyCode 속성 활용
        * keyCode 속성은 입력한 키를 숫자로 나타냄. 37 38 39 40이 방향키 왼쪽, 위, 오른쪽, 아래를 나타냄
         */
         document.addEventListener('DOMContentLoaded', () => {
             // 별의 초기 설정
             const star = document.querySelector('h1')
             star.style.position = 'absolute'; // style 속성을 조작하여 position 값을 설정
             star.style.transitionDuration = '2s';

             // 별의 이동을 출력하는 기능
             let [x,y] = [5,5];
             const block = 20;
             const print = () => {
                 star.style.left = `${x * block}px`;
                 star.style.top = `${y * block}px`;
             }
             print();

             // 별을 이동하는 기능
             const [left, up, right, down] = [37, 38, 39, 40] // 방향키 keyCode를 쉽게 사용하기 위해 변수를 사용해 이름을 붙임
             document.body.addEventListener('keydown', (event)=> { // 키보드 눌릴 때 실행
                 switch (event.keyCode) {
                     case left:
                         x-=1;
                         break;
                     case up:
                         y -=1;
                         break;
                     case right:
                         x += 1;
                         break;
                     case down:
                         y +=1;
                         break;
                 }
                 print()
             });
             // 별 색깔, 크기를 변경하는 기능
             const rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
             const sizes = [10 ,20, 30, 40, 50]
             let idx = 0;
             setInterval(function () {
                 star.style.color = rainbow[idx++%rainbow.length]
                 star.style.size = sizes[idx++%sizes.length]
             }, 500)
         });
    </script>
</head>
<body>
    <h1>★</h1>
</body>
</html>

 

6. form 태그 관련

 - 입력 양식을 기반으로 inch를 cm 단위로 변환하는 프로그램

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <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)) { // 숫자가 아니라면 바로 리턴. isNaN()함수 : 숫자가 아닌지 확인. not a Number
                    p.textContent = '숫자를 입력해주세요.'
                    return;
                }

                // 변환해서 출력
                const cm = inch * 2.54;
                p.textContent = `${cm} cm`;
            })
        })
    </script>
</head>
<body>
    <input type="text"> inch<br>
    <button>계산</button>
    <p></p>
</body>
</html>

 

 - 이메일 형식 확인하기

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /*
        form 태그 관련
        이메일 형식 확인하기
         */
        document.addEventListener('DOMContentLoaded', ()=> {
            const input = document.querySelector('input');
            const p = document.querySelector('p');

            const isEmail = (value) => { // 이메일인지 검사하는 함수
                // 골뱅이를 갖고 있고 && 골뱅이 뒤에 점이 있다면
                return (value.indexOf('@')>1) && (value.split('@')[1].indexOf('.')>1);
            };

            input.addEventListener('keyup', function(event) {
                const value = event.currentTarget.value;
                // const value = input.value;
                console.log(value);

                if (isEmail(value)) {
                    p.style.color = 'green'
                    p.textContent = `이메일 형식입니다: ${value}`;
                }
                else {
                    p.style.color = 'red';
                    p.textContent = `이메일 형식이 아닙니다: ${value}`;
                }
            })
        })
    </script>
</head>
<body>
    <input type="text">
    <p></p>
</body>
</html>

 

 


공부 과정을 정리한 것이라 내용이 부족할 수 있습니다.

부족한 내용은 추가 자료들로 보충해주시면 좋을 것 같습니다.

읽어주셔서 감사합니다 :)