본문 바로가기

JS-DOM

02. Event

1. Event

 

 

 

Event 는 어떤 “사건” 을 의미 한다.

 

아래는 가장 일반적으로 사용하는 이벤트 속성이다.

 

Event Description
onchange Html 문서가 변경이 있을 경우 작동(예: select 변경 등)
onclick 클릭시
onmouseover 마우스가 위로 올라왔을 경우
onmouseout 마우스가 특정 영역을 벗어 났을 경우
onkeydown 키가 눌렸을 경우
onload 브라우저가 모든 페이지를 로딩 한 후

 

 

 

<html>
    <head>
        <meta charset="UTF-8">
        <title>DOM SCRIPT</title>
        <link rel="icon" href="../img/img01.jpg">
        <style>
            div{
                width: 250px;
                height: 250px;
                background-color: yellowgreen;
            }
        </style>
    </head>
    <!-- onload : html 문서가 다 읽히면 발생하는 이벤트 -->
    <body onload="console.log('loading end');">
        <!-- 이벤트는 한 요소에 다수개를 적용할 수 있다. -->
        <div onmouseover="mouseEvt('over')" onmouseout="mouseEvt('out')"></div>
        <!-- inline 속성을 가지고 있는 영역 태그 -->
        <h3>오늘의 날짜 : <span id="demo"></span></h3>
        <input type="button" onclick="getDay()" value="날짜 추출"/>

        <input type="text" id="keyon" onkeydown="keyon()"/>
        <input type="text" id="keyup" onkeyup="keyup()"/>
        <h4 id="typing"></h4>

        <select id="mySelect" onchange="selectOne()">
            <option value="Audi">Audi</option>
            <option value="BMW">BMW</option>
            <option value="Benz">Benz</option>
            <option value="Volvo">Volvo</option>
        </select>
    </body>
    <script>
        function selectOne(){
            // 1. id="mySelect" 인 요소 가져오기
            var elem = document.getElementById('mySelect');
            // 2. 요소에서 속성 가져오기 (value)
            var val = elem.value;
            // console.log(val);
            // 3. id="typing" 인 요소 가져오기
            elem = document.getElementById('typing');
            // console.log(elem);
            // 4. 요소에서 속성 입력하기 (innerHTML="")
            elem.innerHTML = val;
        }

        function keyon(){ // keydown : 키 입력 자체를 체크할 경우
            // 키를 누르면 일단 값을 가져오기 때문에, 아직 입력되어 문자화 되어 찍힌 값을 가져오지 못한다.
            var msg = document.getElementById('keyon').value;
            document.getElementById('typing').innerHTML = msg;
        }

        function keyup(){ // keyup : 입력한 값을 가져올 경우
            var msg = document.getElementById('keyup').value;
            document.getElementById('typing').innerHTML = msg;
        }


        function getDay(){
            var date = new Date();
            console.log(date);
            // id="demo" 에 날짜 값을 표시하시오.
            var elem = document.getElementById('demo');
            elem.innerHTML = date;
            // document.getElementById('demo').innerHTML = date;
        }


        var elem = document.getElementsByTagName('div');

        function mouseEvt(arg){ // 이벤트에서 무언가를 넘겨주면 함수에서 받을 수 있다.
            elem[0].style.backgroundColor = 'red';
            if (arg == 'out') {
                elem[0].style.backgroundColor = 'yellowgreen';
            }
            console.log('mouse ' + arg);
        }
    </script>
</html>

 

 

 

 

 

2. Event 객체와 this

 

 

 

이벤트가 발생할 경우 이벤트 객체 가 반환 된다.

 

그리고 이벤트가 발생한 당사자 요소this 도 있다.

 

이 두 객체를 활용하면 복잡한 내용도 쉽게 해결 할 수 있다.

 

 

Event Description
event 객체 발생한 이벤트에 대한 모든 정보를 담고 있는 객체
this 객체 이벤트가 발생한 당사자 요소를 담고 있는 객체

 

 

<html>
    <head>
        <meta charset="UTF-8">
        <title>DOM SCRIPT</title>
        <link rel="icon" href="../img/img01.jpg">
        <style>

        </style>
    </head>
    <body>
        <button onclick="arg1(event)">버튼 1</button>
        <button onclick="arg1(this)">버튼 2</button>
        <!-- 둘 다 받으면? -->
        <p>
            <a href="#" onclick="arg2(event,this)">클릭 1</a>
        </p>
        <p>
            <a href="#" onclick="arg2(event,this)">클릭 2</a>
        </p>
        <p>
            <a href="#" onclick="arg2(event,this)">클릭 3</a>
        </p>
    </body>
    <script>
        function arg1(obj){
            // event : 일어난 이벤트와 관련된 모든 내용
            // this : 이벤트가 일어난 당사자
            console.log('object : ', obj)
        }
        function arg2(evt,elem){
            // console.log(evt);
            // console.log(elem);
            // elem 를 통해 innerHTML 가져오기
            var str = elem.innerHTML;
            // str 출력하기
            console.log(str);
        }

    </script>
</html>

 

 

 

 

 

3. Event Listener

 

 

 

Event Listener 는 특정 요소에 특정 이벤트를 감시하는 기능을 추가하는 개념이다.

 

element.addEventListener("event", function)

 

Event Listener 에 등록 할 수 있는 이벤트는 속성에 추가한 이벤트 에서 on 만 빠진 형태 이다.

 

 

<html>
    <head>
        <meta charset="UTF-8">
        <title>DOM SCRIPT</title>
        <link rel="icon" href="../img/img01.jpg">
        <style>
            div{
                width: 250px;
                height: 250px;
                background-color: yellowgreen;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <h4 id="msg">FOCUS NULL</h4>
        <p><input type="text" id="txtinput"/></p>
        <div id="eventZone"></div>
        <h4>mouse position : <span id="pos"></span></h4>
    </body>
    <script>
        // 요소 가져오기
        var msg = document.getElementById('msg');
        // console.log(msg);
        var txtinput = document.getElementById('txtinput');
        // console.log(txtinput);
        var zone = document.getElementById('eventZone');
        // console.log(zone);
        var pos = document.getElementById('pos');
        // console.log(pos);

        // 이벤트걸 요소.addEventListener('이벤트명', 호출할 함수);
        txtinput.addEventListener('focusin', fcsin);
        // focusout 이벤트 발생시 fcsout 함수 호출 하도록
        txtinput.addEventListener('focusout', fcsout);

        // msg 에 console 에 찍히는 내용을 적용해 보세요.
        function fcsin(){
            console.log('FOCUS IN');
            msg.innerHTML = 'FOCUS IN';
            this.style.backgroundColor = 'red';
        }

        function fcsout(e){
            console.log(e); // 이벤트 객체
            console.log(this); // 이벤트 발생한 당사자
            console.log('FOCUS OUT');
            msg.innerHTML = 'FOCUS OUT';
            // this.style.backgroundColor = 'blue';
            // this 대신 이벤트 객체로 this 역할을 할 수 있다.
            console.log(e.target);
            e.target.style.backgroundColor = 'blue';
        }

        // txtinput 에 keyup 이벤트가 발생되면 msg 에 입력 내용이 표시되도록 하자.
        txtinput.addEventListener('keyup', function(e){
            console.log(e);
            console.log(e.keyCode); // 엔터
            var val = txtinput.value;
            console.log(val);
            msg.innerHTML = val;
            if (e.keyCode == 13) {
                txtinput.value = '';
                alert('입력 내용이 전송 되었습니다.')
            }

        });

        // zone - 마우스가 들어가면 (mouseenter)
        zone.addEventListener('mouseenter', callback);
        // zone - 마우스가 나가면 (mouseout)
        zone.addEventListener('mouseout', callback);
        // zone - 마우스가 클릭하면 (click)
        zone.addEventListener('click', callback);
        // zone - 마우스가 더블클릭하면 (dblclick)
        zone.addEventListener('dblclick', callback);

        function callback(e){
            var type = e.type;
            console.log(e.type);
            e.target.innerHTML = '<h3>' + type + '<h3/>';
            if (type == 'click') {
                e.target.style.backgroundColor = 'orange';
            }else if (type == 'dblclick') {
                e.target.style.backgroundColor = 'red';
            }else if (type == 'mouseenter') {
                e.target.style.backgroundColor = 'yellow';
            }else {
                e.target.style.backgroundColor = 'yellowgreen';
            }
        }

        // 이벤트를 html 문서 전체에 걸어준다.
        document.addEventListener('mousemove', function(evt){
            // console.log(evt.clientX + '/' + evt.clientY);

            pos.innerHTML = 'X : ' + evt.clientX + ' / Y : ' + evt.clientY;
        });

    </script>
</html>

 

 

<html>
    <head>
        <meta charset="UTF-8">
        <title>DOM SCRIPT</title>
        <link rel="icon" href="../img/img01.jpg">
        <style>
            
        </style>
    </head>
    <body>
        <h1 id="txt">글자 색상이 변경됩니다.</h1>
        <button id="btn" onclick="change()">색상 변경</button>
    </body>
    <script>
        var count = 0;
        var arr = ['red', 'orange', 'yellow', 'green', 'blue', 'navy', 'blueviolet'];
        var elem = document.getElementById('txt');
        function change() {
            // count++;
            // if (count == 1) {
            //     elem.style.color = 'red';
            // }else if (count == 2) {
            //     elem.style.color = 'orange';
            // }else if (count == 3) {
            //     elem.style.color = 'yellow';
            // }else if (count == 4) {
            //     elem.style.color = 'green';
            // }else if (count == 5) {
            //     elem.style.color = 'blue';
            // }else if (count == 6) {
            //     elem.style.color = 'navy';
            // }else if (count == 7) {
            //     elem.style.color = 'blueviolet';
            //     count = 0;
            // }
            elem.style.color = arr[count];
            count++;
            if (count == 7) { 
                count = 0;
            }
        }
    </script>
</html>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'JS-DOM' 카테고리의 다른 글

04. 부모-자식 창, alert, timing, JSON  (0) 2024.03.08
03. Window Object  (0) 2024.03.08
01. JS-DOM의 기초  (0) 2024.03.08