본문 바로가기
프로그래밍/예제로 배우는 자바스크립트 요약 및 분석(IT 전공 서적)

예제로 배우는 자바스크립트 요약 및 코드 분석 12장 12.1~12.3

by 리드민 2023. 10. 18.
반응형

12.1 이벤트란?

  이벤트(event)는 웹 페이지에서 발행하는 사건을 의미한다. 자바스크립트에서는 이벤트가 발생하면 이벤트를 감지하고 처리할 수 있다. 사용자의 마우스 조작과 키보드 입력은 하나의 이벤트이며 HTML 문서 로드나 에러 발생 들도 일종의 이벤트이다. 이벤트를 처리하는 함수를 이벤트 핸들러(event handler) 또는 이벤트 리스너(event listener)라고 합니다.

 

12.1.1 이벤트 핸들러

  마우스 클릭이나 이동, 페이지 로드, 이미지 로드, 입력창에 데이터 입력, 키보드 누르기 등에 따라 발생되는 이벤트를 처리하기 위해 자바스크립트에서는 이벤트 핸들러(event handler)를 사용한다.

  다음은 버튼을 클릭했을 때 이벤트 핸들러를 통해 요소 내에 있는 텍스트를 변경해주는 예이다. 여기서는 <button> 요소의 onclick 속서엥 이벤트 핸들러를 설정한다.

예제 12-1. 이벤트 핸들러 사용 예 event_handler.html 코드 원문
<button onclick="changeText(this)">클릭하세요!</button>
<script>
    function changeText(elem) {
        elem.innerHTML = "OK!";
    }
</script>
예제 12-1. 이벤트 핸들러 사용 예 event_handler.html 코드 분석
<button onclick="changeText(this)">클릭하세요!</button>
/* 버튼 '클릭하세요!'를 클릭하면 onclick에 설정된 이벤트 핸들러
changeText()가 동작하여 문장에 의해 버튼의 내용이 'OK!'로 변경된다. */
<script>
    function changeText(elem) {
        elem.innerHTML = "OK!";
=    }
</script>

 

12.1.2 인라인 모델

  아주 간단하게 이벤트를 처리하는 데는 앞의 이벤트 핸들러를 사용하지 않고 다음과 같이 HTML 태그의 이벤트 속성에 코드를 직접 삽입하여 이벤트를 처리할 수도 있다. 이와 같이 이벤트를 처리하는 것을 인라인 모델이라고 한다.

예제 12-2. 인라인 모델에서 이벤트 처리 예 event_inline.html 코드 원문
<button onclick="document.getElementById('show').innerHTML = Date()">현재 시간은</button>
<p id="show"></p>
예제 12-2. 인라인 모델에서 이벤트 처리 예 event_inline.html 코드 원문
<button onclick="document.getElementById('show').innerHTML = Date()">현재 시간은</button>
// 버튼을 누르면 현재시간을 출력한다.
<p id="show"></p>

 

12.1.3 이벤트 리스너

  이벤트 리스너(event listerner)는 이벤트 핸들러와 거의 동일한 개념이다. 이벤트 리스너는 이벤트 핸들러와 마찬가지로 이벤트를 처리하는 함수를 의미한다. 리스너는 이벤트가 발생하길 기다렸다가 이벤트 발생 시 해당 이벤트를 처리한다. 이벤트 핸들러는 이벤트 속성에 바로 대입하여 사용하는 데 반해 리스너는 addEventListner() 메서드를 이용하여 리스너를 등록한 다음 사용한다.

  다음 예제를 통하여 addEventListener() 메서드의 사용법에 대해 알아보자.

예제 12-3. addEventListener()로 리스너 등록하기 event_listener.html 코드 원문
<button id="btn">클릭하세요!</button>
<p id="show"></p>
<script>
    let text = "";

    document.getElementById("btn").addEventListener("click", function() {
        text += "안녕하세요!<br>";
        document.getElementById("show").innerHTML = text;
    });
    document.getElementById("btn").addEventListener("click", function() {
        text += "반갑습니다!<br>";
        document.getElementById("show").innerHTML = text;
    })
</script>
예제 12-3. addEventListener()로 리스너 등록하기 event_listener.html 코드 분석
<button id="btn">클릭하세요!</button>
<p id="show"></p>
<script>
    let text = "";

    document.getElementById("btn").addEventListener("click", function() {
    // id btn을 눌렸을때 동작하는 함수 addEventListener 선언
        text += "안녕하세요!<br>";
        // 문자열 '안녕하세요!를 변수 text에 저장
        document.getElementById("show").innerHTML = text;
        // 변수 text에 저장된 내용을 id가 show인 곳에 출력
    });
    document.getElementById("btn").addEventListener("click", function() {
    // id btn을 눌렸을때 동작하는 함수 addEventListenr 선언
        text += "반갑습니다!<br>";
        // 문자열 '반갑습니다!<br>'를 변수 text에 저장
        document.getElementById("show").innerHTML = text;
        // 변수 text에 저장된 내용을 id가 show인 곳에 출력
    })
</script>

 

12.2 이벤트 버블링

  이벤트는 일반적으로 하나의 객체에 대해 발생하지만 어떤 경우에는 하나의 객체에서 발생된 이벤트가 상위 객체로 전달되기도 한다. 이것을 이벤트 버블링(event bubbling)이라고 한다. 이벤트 버블링은 거품이 일어나듯이 이벤트가 전달된다는 의미를 갖고 있다.

예제 12-4. 이벤트 버블링 발생 예 event_bubbling.html 코드 원문
<style>
    div, p, img { margin: 10px; border: 1px solid green;}
</style>
<div onclick="alert('div 입니다!')">
    <p onclick="alert('p 입니다!')">
        <img src="img/dog.png" onclick="alert('img 입니다!')">
    </p>
</div>
예제 12-4. 이벤트 버블링 발생 예 event_bubbling.html 코드 원문
<style>
    div, p, img { margin: 10px; border: 1px solid green;}
</style>
<div onclick="alert('div 입니다!')">
<!-- <div> 요소에 설정된 코드에 의해 'div 입니다!'가 알림창에 출력된다. -->
    <p onclick="alert('p 입니다!')">
    <!-- <p>에 onclick 속성에 설정된 코드에 의해 'p 입니다!'가 알림창에 출력된다. -->
        <img src="img/dog.png" onclick="alert('img 입니다!')">
        <!-- 이미지를 클릭하면 'img 입니다!'라는 문자열이 뜨게 onclick 속성에 뜨게 한다. -->
    </p>
</div>

  클릭(click) 이벤트에서는 내부 요소에서 하나의 이벤트가 발생되면 상위 요소에게까지 그 이벤트가 전달된다. 여러 요소가 발생된 이벤트를 전달받지만 이벤트 처리가 필요한 요소에서만 이벤트 핸들러를 통해 이벤트를 처리하면 되기 때문에 이벤트 버블링은 실 사용에 별 문제가 되지 않는다.

  만약 이벤트가 제일 먼저 발생된 요소를 구별하려고 할 때는 프로퍼티 event.target을 이용한다. 다음 예제는 event.target을 이용해서 앞의 예제에서 클릭 이벤트를 발생시킨 요소의 태그 이름을 찾는다.

 

예제 12-5. event.targer 사용 예 event_targer.html 코드 원문
<style>
    div, p, img { margin: 10px; border: 1px solid green;}
</style>
<div onclick="func(event)">
    <p>
        <img src="img/dog.png">
    </p>
</div>
<span id="show"></span>
<script>
    function func(event) {
        let text = event.target.tagName;
        document.getElementById("show").innerHTML = text;
    }
</script>
예제 12-5. event.targer 사용 예 event_targer.html 코드 원문
<style>
    div, p, img { margin: 10px; border: 1px solid green;}
</style>
<div onclick="func(event)">
<!-- onclick 이벤트 선언 클릭 시 메서드 func(event)가 실행된다. -->
    <p>
        <img src="img/dog.png">
    </p>
</div>
<span id="show"></span>
<script>
    function func(event) {
        let text = event.target.tagName;
        document.getElementById("show").innerHTML = text;
    }
</script>

 

12.3 마우스 이벤트

  마우스에 관련된 이벤트는 웹에서 가장 많이 사용되는 이벤트 중에 하나이다. MouseEvent 객체는 웹 페이지에서 마우스 조작으로 발생되는 이벤트를 다루는 데 사용된다. 많이 사용되는 마우스 이벤트를 정리하면 다음 표와 같다.

마우스 이벤트
이벤트 발생 시점
onclick 사용자가 요소를 클릭했을 때
ondblclick 사용자가 요소를 더블 클릭했을 때
onmouseover 마우스 포인터가 요소 위에 올라갔을 때
onmouseenter 마우스 포인터가 요소에서 벗어날 때
onmouseleave 마우스 포인터가 요소 안으로 진입할 때
onmousemove 마우스 포인터가 요소에서 외부로 나갈 때
onmousemove 마우스 포인터가 요소안에서 움직일 때

  onmouseover/onbmouseout은 자식 요소에 대해서도 동작하지만, onmouseenter/onmouseleave는 자식 요소에 대해서는 동작하지 않는다.

 

12.3.1 onclick/ondblclick 이벤트

  다음 예제를 통해서 onclick과 ondblclick 이벤트에 대해 알아보자.

예제 12-6. onclick/ondblclick 이벤트 사용 예 onclick.html 코드 원문
<button onclick="showMessage1()">클릭하세요!</button><br>
<button ondblclick="showMessage2()">더블 클릭하세요!</button>
<p id="show"></p>
<script>
    function showMessage1() {
        document.getElementById("show").innerHTML = "클릭했어요!";
    }
    function showMessage2() {
        document.getElementById("show").innerHTML = "더블 클릭했어요!";
    }
</script>
예제 12-6. onclick/ondblclick 이벤트 사용 예 onclick.html 코드 원문
<button onclick="showMessage1()">클릭하세요!</button><br>
<button ondblclick="showMessage2()">더블 클릭하세요!</button>
<p id="show"></p>
<script>
    function showMessage1() {
        document.getElementById("show").innerHTML = "클릭했어요!";
    }
    function showMessage2() {
        document.getElementById("show").innerHTML = "더블 클릭했어요!";
    }
</script>

  '클릭하세요!' 버튼을 클릭하면 이벤트 핸들러 showMessage1()에 의해 '클릭했어요!' 메시지가 <p> 요소에 출력된다. 그리고 '더블 클릭하세요!' 버튼을 더블 클릭하면 showMessage2()가 동작하여 '더블 클릭했어요!'란 메시지가 출력된다.

 

12.3.2 onmouseover/onbmouseout 이벤트

  다음 예제는 onbmouseover와 onbmouseout 이벤트를 이용하여 버튼 요소에 마우스를 올렸다 내렸을때 요소의 배경 색상을 변경하는 프로그램이다.

예제 12-7. onmouseover/onmouseout 이벤트 사용 예 onmouseover.html 코드 원문
<button onmouseover="changeBg1(this)" onmouseout="changeBg2(this)">
    마우스를 올려보세요!</button><br>
<script>
    function changeBg1(x) {
        x.style.backgroundColor = "yellow";
    }
    function changeBg2(x) {
        x.style.backgroundColor = "";
    }
</script>
예제 12-7. onmouseover/onmouseout 이벤트 사용 예 onmouseover.html 코드 원문
<button onmouseover="changeBg1(this)" onmouseout="changeBg2(this)">
/* 버튼 위에 마우스를 가져다대면 버튼 배경 색상이 노란색으로 변경된다.
마우스를 내렸을 경우에는 버튼의 배경색이 원래대로 돌아온다. */
    마우스를 올려보세요!</button><br>
<script>
    function changeBg1(x) {
        x.style.backgroundColor = "yellow";
    }
    function changeBg2(x) {
        x.style.backgroundColor = "";
    }
</script>

  다음 그림 12-7에 나타난 것과 같이 버튼 위에 마우스를 가져다대면 버튼의 배경 색상이 노란색으로 변경되고 마우스를 내렸을 경우에는 버튼의 배경색이 원래대로 돌아온다.

 

12.3.3 onmouseenter 이벤트

  onmouseenter 이벤트는 앞에서 설명한 onmouseover 이벤트와 유사한 기능을 수행한다. 다음 예제를 통해서 둘 간의 차이에 대해 알아보자.

예제 12-8. onmouseenter와 onmouseover 이벤트에 차이점 onmouseenter.html 코드 원문
<style>
    div#box1 { border: solid 3px red; }
    div#box2 { border: solid 3px blue; }
    p { border: solid 1px black; }
</style>
<div id="box1" onmouseenter = "increase"><()">
    <p>단락1</p>
    <span id="show1"></span>
</div>
<div id="box2" onmouseover="increaseY()">
    <p>단락2</p>
    <span id="show2"></span>
</div>
<script>
    let x = 0, y = 0;
    function increaseX() {
        x += 1;
        document.getElementById("show1").innerHTML = x;
    }
    function increaseY() {
        y += 1;
        document.getEleemntById("show2").innerHTML = y;
    }
</script>
예제 12-8. onmouseenter와 onmouseover 이벤트에 차이점 onmouseenter.html 코드 분석
<style>
    div#box1 { border: solid 3px red; }
    div#box2 { border: solid 3px blue; }
    p { border: solid 1px black; }
</style>
<div id="box1" onmouseenter = "increase"><()">
    <p>단락1</p>
    <span id="show1"></span>
</div>
<div id="box2" onmouseover="increaseY()">
    <p>단락2</p>
    <span id="show2"></span>
</div>
<script>
    let x = 0, y = 0;
    function increaseX() {
        x += 1;
        document.getElementById("show1").innerHTML = x;
    }
    function increaseY() {
        y += 1;
        document.getEleemntById("show2").innerHTML = y;
    }
</script>

  onmouseleave 이벤트의 경우에는 자신의 요소에서 마우스가 벗어났을 때만 이벤트가 발생하는 반면 onmouseover 이벤트는 자신의 요소뿐만 아니라 자식 요소들에서 마우스가 벗어날 때도 이벤트가 발생된다.

 

12.3.5 onmousemove 이벤트

  onmousemove 이벤트는 요소 내에서 마우스가 이동할 때 발생된다.

예제 12-10. onmousemove 이벤트 사용 예 onmousemove.html 코드 원문
<style>
    div#box { border: solid 3px black; width: 300px; height: 200px;}
</style>
<div id="box" onmousemove="showCoord(event)">
    <p id="show"></p>
</div>
<script>
    function showCoord(e) {
        let text = "좌표 : (" + e.clientX + ", " + e.clientY + ")";
        document.getElementById("show").innerHTML =text;
    }
</script>
예제 12-10. onmousemove 이벤트 사용 예 onmousemove.html 코드 분석
<style>
    div#box { border: solid 3px black; width: 300px; height: 200px;}
</style>
<div id="box" onmousemove="showCoord(event)">
<!-- id를 'box'로 하고 마우스의 이동 이벤트 onmousemove 이벤트에 showCoord 메서드를 연결한다. -->
    <p id="show"></p>
</div>
<script>
    function showCoord(e) {
        let text = "좌표 : (" + e.clientX + ", " + e.clientY + ")";
        /* text 변수에 문자열 "좌표 : (" + e.clentX + ", " + e.clientY를 저장한다. */
        document.getElementById("show").innerHTML =text;
    }
</script>

  검정색 박스 안에서 마우스를 움직이면 가로와 세로 좌표 값이 화면에 나타난다. onmousemove 이벤트는 마우스가 움직일 때 픽셀 단위로 동작한다. event 객체의 clientX와 ClientY는 각각 브라우저 화면을 기준으로 X축과 Y축의 좌표를 의미한다.

반응형