자바스크립트 체크 이벤트

이세라·2024년 10월 1일
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>체크 이벤트</title>
    <style>
        #checkbox{
            width: 20px;
            height: 20px;
        }
        h1{
            font-size: 20px;
        }
    </style>
    <script>
    document.addEventListener("DOMContentLoaded",function(){
        let timer = 0;
        let timerid = 0; //setInterval
//      let [timer, timerid]=[0,0] // 자바스크립트, 파이썬에서만 사용가능
        const checkbox = document.querySelector("#checkbox");
        const h1 = document.querySelector("#time");

//      checkbox의 체크 여부에 따른 이벤트 처리
        checkbox.addEventListener("change",function(event){ 
        //체크 상태일 때
        if(event.currentTarget.checked){ //event.currentTarget : 현재 작업 상태에 있는 요소
                                                            // 이벤트를 발생시킨 요소
            timerid = setInterval(function(){
                timer++; //timer = timer + 1; timer += 1;
//              h1.textContent="현재 활성화된 시간: + timer + "초";
                h1.textContent=`현재 활성화된 시간: ${timer}`;
            },1000);
        }else{//체크 해제 상태일 때
            clearInterval(timerid); //시간을 멈춤, setInterval()함수 실행 멈춤
        }//end of if
        });//end of setInterval        

    }); //end of DOM
    
    </script>
</head>
<body>
    <input type="checkbox" id="checkbox" name="timeCheck">
    <h1 id="time">0초</h1>
</body>
</html>
profile
개린이입니다...

0개의 댓글