잿꽃's posting Garden

자바스크립트로 간단한 Space Counter(스페이스 카운터) 만들기 본문

WEB/JAVASCRIPT

자바스크립트로 간단한 Space Counter(스페이스 카운터) 만들기

잿꽃 2022. 3. 10. 14:43

간단한 Space Counter(스페이스 카운터) 만들기

스페이스 바를 누르면 카운터 되는 아주 간단한 코딩을 해보았습니다. 

별거 아니지만 독특한 걸 만들어보고 싶어서 제작해 보았습니다. 간단하기 때문에 HTML안에 CSS와 Javascript를 함께 작성했습니다.

 

 

순서도

1. 스페이스 버튼을 누르고 뗀다

2. 화면에 횟수를 보여준다

3. 버튼을 누르면 카운터를 리셋한다.

 

 

HTML

<!DOCTYPE html>
<html lang="en">

<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>Document</title>
</head>
    <style>
        div{
            width: 100%;
            height: 300px;
            background: #ececec;
            position: relative;
        }
        p, button{
            position: absolute;
            left: 0;
            right: 0;
            margin: 0 auto;
            text-align: center;
        }
        p{
            width: 40%;
            top: 50px;
            font-size: 1.75em;
        }
        span{
            font-size: 2em;
            color: red;
        }
        button{
            width: 20%;
            height: 50px;
            bottom: 80px;
            font-size: 1.25em;
            background: #333;
            color: #fff;
            border: none;
        }
        button:hover{
            color: darkred;
        }
    </style>
<body>
    <div>
        <p>Press SpaceBar <span id="press">0</span> times</p>
        <button onclick="reset()">RESET COUNTER</button>
    </div>
    <script>
        //span태그에 접근
        const num = document.getElementById('press');
        //button태그에 접근
        const btn = document.querySelector('button');
        //press counter 초기값
        let counter = 0;

        //문서에서 키 누름 후 뗄 때 if에서 스페이스 키 코드를 확인해서 counter를 올림
        document.onkeyup = e => {
            if(e.keyCode == 32){
                ++counter;
                num.textContent = counter;
                //console.log(counter);
            }
        }

        //버튼을 누르면 counter를 리셋
        function reset(){
            counter = 0;
            num.innerHTML = counter;
            //버튼 focus상태해제
            btn.blur();
        }
    </script>
</body>

</html>

onkeyup메소드를 통해서 키를 떼었을 때 함수가 작동됩니다.

스페이스 코드는 32번으로 키 코드가 32번일 경우 화면에 있는 숫자가 올라가게 됩니다.

 

 

 

스페이스 카운터의 초기값과 스페이스를 눌러 숫자가 올라간 모습
초기값과 카운트 된 모습

 

728x90
Comments