1.  키보드 이벤트

이벤트 설명
keydown 키가 눌릴 때 실행. 키보드를 꾹 누르고 있을 때도, 입력될 때도 실행
keypress 키가 입력되었을 때 실행. 공백이 들어가기 전까지 글자수를 세지 x
웹 브라우저에 따라서 아시아권의 문자를 제대로 처리 못하는 문제가 있음
keyup 키보드에서 키가 떨어질 때 실행

 

<head>
    <script>
        // 남은 글자수 출력하기
        document.addEventListener('DOMContentLoaded', () => {
            const textarea = document.querySelector('textarea');
            const h1 = document.querySelector('h1');

            textarea.addEventListener('keyup', () => { // 키보드에서 키가 떨어질 때 실행
                // value 속성으로 입력양식(form 태그)의 글자(문자열)을 읽을 수 있음.
                const length = textarea.value.length
                h1.textContent = `글자 수: ${length}`;
            })

            textarea.focus();
        });
    </script>
</head>
<body>
    <h1>글자 수: 0</h1>
    <textarea></textarea>
</body>


2.  키보드 키 코드 사용하기

키보드 이벤트 관련 속성
이벤트 속성 이름 설명
code 입력한 키
keyCode 입력한 키를 나타내는 숫자
altKey Alt 키를 눌렀는지
ctrlKey Ctrl 키를 눌렀는지
shiftKey Shift 키를 눌렀는지 


   👩🏻‍💻  code 속성은 입력한 키를 나타내는 문자열이 들어있고
         altKey, ctrlKey, shiftKey 속성은 해당 키를 눌렀는지 불 자료형이 들어 있음

<head>
    <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>

 


keyCode 속성 활용 

 

    keyCode 속성은 입력한 키를 숫자로 나타냄. 37, 38, 39, 40이 방향키 왼쪽, 위, 오른쪽, 아래를 나타냄

<head>
    <script>       
        document.addEventListener('DOMContentLoaded', () => {
            // 별의 초기 설정
            const star = document.querySelector('h1');
            star.style.position = 'absolute'; // style 속성을 조작하여 position 값을 설정
            star.style.transitionDuration = '1s';

            // 별의 이동을 출력하는 기능
            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 colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
            const size = [10, 20, 30, 40, 50];
            let index = 0;
            setInterval(() => {
                star.style.color= colors[index++ % colors.length];
                star.style.fontSize = String(size[index++ % size.length]) + 'px'
            }, 500)

        });
    </script>
</head>
<body>
    <h1>★</h1>
</body>

 


3.  이벤트 발생 객체

(1) 이벤트 리스너를 외부로 빼낸 경우

<script>
const listener = (event) => {
    const length = textarea.value.length
    h1.textContent = `글자 수: ${length}`
}

document.addEventListener('DOMContentLoaded', () => { // 외부로 분리
    const textarea = document.querySelector('textarea')
    const h1 = document.querySelector('h1')
    textarea.addEventListener('keyup', listener)
})    
</script>

 

  👩🏻‍💻  코드의 규모가 커지면 위와 같이 이벤트 리스너를 외부로 분리하는 경우가 많아짐

 

이벤트를 발생시킨 객체에 접근하는 방법

 

    📌  event.currentTarget 속성을 사용

         - () => {} 와 function () {} 형태 모두 사용 가능

    📌  this 키워드를 사용

         - 화살표 함수가 아닌 function () {} 형태로 함수를 선언한 경우에 사용

 

currentTarget 속성 사용
<script>
const listener = (event) => {
    const length = event.currentTarget.value.length
    // event.currentTarget이 textarea
    h1.textContent = `글자 수: ${length}`
}

document.addEventListener('DOMContentLoaded', () => { // 외부로 분리
    const textarea = document.querySelector('textarea')
    const h1 = document.querySelector('h1')
    textarea.addEventListener('keyup', listener)
})    
</script>

 

this 키워드 사용
<script>
const listener = function (event) {
    const length = this.value.length
    // this가 textarea
    h1.textContent = `글자 수: ${length}`
}

document.addEventListener('DOMContentLoaded', () => { // 외부로 분리
    const textarea = document.querySelector('textarea')
    const h1 = document.querySelector('h1')
    textarea.addEventListener('keyup', listener)
})    
</script>

 


 

(2) 글자 입력 양식 이벤트

 

  👩🏻‍💻  입력 양식 form : 사용자로부터 어떠한 입력을 받을 때 사용하는 요소

            ex. input, textarea, button, select

 

입력 양식을 기반으로 inch를 cm 단위로 변환하는 프로그램
<head>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const input = document.querySelector('input');
            const btn = document.querySelector('button');
            const p = document.querySelector('p');

            btn.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>

 


 

이메일 형식 확인하기
<head>
    <script>

        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>

 

 

[ 내용참고 : IT 학원 강의 및 책 '혼자 공부하는 자바스크립트' ]

+ Recent posts