본문 바로가기

웹개발관련/javascript 관련 정리

자바스크립트 이벤트 처리 예시

이벤트 종류

이벤트 이름 설명
load  페이지의 로드가 완료되었을 
unload  페이지가 언로드될 (주로 새로운 페이지를 요청한 경우), 브라우저가 자바스크립트 오류를 만났거나 요청한 자원이 존재하지 않는 경우
error 브라우저가 자바스크립트 오류를 만났거나 요청한 자원이 존재하지 않는 경우
resize 브라우저 창의 크기를 조절했을 
scroll 사용자가 페이지를 위아래로 스크롤할 
select 텍스트를 선택했을 
keydown 키를 누르고 있을 
keyup 누르고 있던 키를  
keypress 키를 누르고 뗏을 
click 마우스 버튼을 클릭했을 
dbclick 마우스 버튼을 더블 클릭했을 
mousedown 마우스 버튼을 누르고 있을 
mouseup 누르고 있던 마우스 버튼을  
mousemove 마우스를 움직일  (터치스크린에서 동작하지 않는다)
mouseover 마우스를 요소 위로 움직였을  (터치스크린에서 동작하지 않는다)
mouseout 마우스를 요소 밖으로 움직였을  (터치스크린에서 동작하지 않는다)
focus/focusin 요소가 포커스를 얻었을 
blur/foucusout 요소가 포커스를 잃었을 
input input 또는 textarea 요소의 값이 변경되었을 
change select box, checkbox, radio button 상태가 변경되었을 
submit form submit  (버튼 또는 )
reset reset 버튼을 클릭할  (최근에는 사용  )
cut 콘텐츠를 잘라내기할 
copy 콘텐츠를 복사할 
paste 콘텐츠를 붙여넣기할 
 
<!-- 간단하게  click이벤트, change이벤트 처리 예시-->
    <button onclick="handler();">클릭</button>
    <br>
    <button class="btn">클릭2</button>
    <label>이름</label>
    <input type="text">
    <div id="input" style="display: none;">
        <input class="password" type="password" value="123">
        <button class="show">보여주기</button>
    </div>

    <script>
        function handler(){
            window.alert('클릭이벤트');
        }

        // btn클래스 객체화
        const btn=document.querySelector('.btn');

        //객체에서 onclick 요소 접근하여 클릭 이벤트 이벤트 처리
        // 다른 객체 속서 ㅇ변경
        btn.onclick=function(){
            window.alert('프로퍼티 방식 이벤트')
            document.querySelector('#input')
                .setAttribute('style','display:block')
        }

        const input=document.querySelector('input[type=text]');
        // 리스너를 통해 change 이벤트 처리
        input.addEventListener('change',function(){
            window.alert('eventlistener change 이벤트 발생');
        });

        const password = document.querySelector(".password");
        const show=document.querySelector('.show');

        // 다른 요소들에게도 영향을 주는 이벤트 처리 방식
        function clickHandler(){
            let isShow=false;
            return function(){
                password.setAttribute('type',isShow?'password':'text');
                isShow=!isShow;
                show.innerHTML=isShow?'숨기기':'보여주기';
            }
        }
        show.onclick=clickHandler();
    </script>
 
 
 <!-- ------이벤트 객체를 활용하여 디테일하게 이벤트 처리 예시 ----------->
 
<body>
    <strong id="message"></strong>
    <div class="container">
        <button id="btn1">숨기기1</button>
        <button id="btn2">숨기기2</button>
    </div>
    <a href="http://www.naver.com">네이버</a>
    <form>
        <label for="chkbox">체크박스</label>
        <input type="checkbox" id="chkbox">
    </form>
    <script>
        const link=document.querySelector('a');
        link.addEventListener('click',function(event){
           event.preventDefault()
        })

        const chkbox=document.querySelector('#chkbox')
        chkbox.addEventListener('click',function(e){
        //이벤트가 의 기본동작이 처리되지 않게 해주는 역할 체크박스는 체크가 안됨
           e.preventDefault()
        })
        const msg=document.querySelector('#message')
        const body=document.querySelector('body')
        //이벤트 처리 메스드
        function showType(e){
            console.log(e)
            e.preventDefault()
            msg.innerHTML=e.type+':'+e.keyCode
        }
        //body 태그에 키보드 눌렸을때 땠을때 이벤트 처리
        body.addEventListener('keydown',showType)
        body.addEventListener('keyup',showType)
       
        const container=document.querySelector('.container')
        function hide(e){
            e.target.style.visibility='hidden'
        }
        //container 클래스를 갖는 요소, 안의 요소가 클릭되면 해당 요소 숨김
        container.addEventListener('click',hide)

        function printCoord(e,out){
            // out.innerHTML+='x:'+e.clientX+' y:'+e.clientY
        }
        //클릭 이벤트 발생시 이벤트 처리 부분에서 객체를 받아서 처리도 가능하다
        addEventListener('click',function(e){
            printCoord(e,msg)
        });
    </script>
</body>