Post

[JS] Event

[JS] Event

JavaScript Event 정리

JavaScript에서 이벤트(Event)는 사용자의 동작이나 브라우저의 상태 변화에 반응하여 특정 코드를 실행하는 방식이다.

예를 들어 사용자가 버튼을 클릭하거나, input에 커서를 올리거나, 페이지 로딩이 끝났을 때 JavaScript 함수를 실행할 수 있다.

참고: W3Schools - JavaScript Events


1. 대표적인 HTML Events

Event 발생 시점
onchange HTML 요소의 값이 변경되었을 때
onclick 사용자가 HTML 요소를 클릭했을 때
onmouseover 마우스가 HTML 요소 위로 올라갔을 때
onmouseout 마우스가 HTML 요소 밖으로 나갔을 때
onkeydown 사용자가 키보드 키를 눌렀을 때
onload 브라우저가 페이지 로딩을 완료했을 때

onload 이벤트가 발생한 이후에는 HTML의 정적 요소들이 메모리에 올라와 있다고 볼 수 있다. 따라서 페이지가 모두 준비된 뒤 실행해야 하는 초기 작업을 처리할 때 사용한다.


2. 주요 Event 예제

1) onload

onload는 페이지 로딩이 끝난 뒤 실행된다.

1
<body onload="bodyLoad()">
1
2
3
4
5
6
function bodyLoad() {
  console.log("loading ....");

  const data = document.myform.money.value;
  console.log(isNaN(data));
}

위 코드에서는 페이지가 모두 로딩된 후 bodyLoad() 함수가 실행된다. 이후 name="money"인 input 값을 가져와 숫자인지 확인한다.


2) onfocus

onfocus는 input 요소에 커서가 들어왔을 때 발생한다.

1
<input type="text" id="myinput" onfocus="focusFunc()">
1
2
3
function focusFunc() {
  document.getElementById("myinput").style.background = "gold";
}

입력창을 클릭하거나 선택하면 해당 input의 배경색이 gold로 변경된다.


3) onblur

onblur는 input 요소에서 커서가 빠져나갔을 때 발생한다.

1
<input type="text" id="myinput" onblur="blurFunc()">
1
2
3
function blurFunc() {
  document.getElementById("myinput").style.background = "white";
}

선택이 해제되면 input의 배경색이 다시 white로 변경된다.


4) onchange

onchange는 select, input 등의 값이 변경되었을 때 발생한다.

1
<select name="sel" onchange="selectTag()">
1
2
3
4
function selectTag() {
  const value = document.myform.sel.value;
  alert(value);
}

select 태그에서 다른 option을 선택하면 selectTag() 함수가 실행되고, 현재 선택된 값이 alert로 출력된다.


3. this의 활용

이벤트 함수에 this를 전달하면 이벤트가 발생한 요소 자신을 함수의 인자로 넘길 수 있다.

1
2
3
4
5
<input
  type="text"
  onmouseover="changeColor(this)"
  onmouseout="changeColor2(this)"
>
1
2
3
4
5
6
7
8
9
function changeColor(obj) {
  console.log(obj);
  obj.style.backgroundColor = "gold";
}

function changeColor2(obj) {
  console.log(obj);
  obj.style.backgroundColor = "white";
}

동작 흐름은 다음과 같다.

  1. input 위에 마우스를 올리면 onmouseover 이벤트가 발생한다.
  2. changeColor(this)가 실행된다.
  3. 여기서 this는 현재 이벤트가 발생한 input 태그를 의미한다.
  4. input 태그가 obj 매개변수로 전달된다.
  5. obj.style.backgroundColor = "gold"가 실행되어 배경색이 변경된다.

4. 핵심 요약

Event 발생 시점 실행 함수 역할
onload 페이지 로딩 완료 bodyLoad() 초기 실행 작업
onfocus input에 커서 진입 focusFunc() 배경색 변경
onblur input에서 커서 이탈 blurFunc() 배경색 원복
onchange select 값 변경 selectTag() 선택값 출력
onmouseover 마우스가 요소 위로 진입 changeColor(this) 이벤트 대상 스타일 변경
onmouseout 마우스가 요소 밖으로 이탈 changeColor2(this) 이벤트 대상 스타일 원복

5. 전체 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Event</title>
  <script>
    function bodyLoad() {
      console.log("loading ....");

      const data = document.myform.money.value;
      console.log(isNaN(data));
    }

    function focusFunc() {
      document.getElementById("myinput").style.background = "gold";
    }

    function blurFunc() {
      document.getElementById("myinput").style.background = "white";
    }

    function selectTag() {
      const value = document.myform.sel.value;
      alert(value);
    }

    function changeColor(obj) {
      console.log(obj);
      obj.style.backgroundColor = "gold";
    }

    function changeColor2(obj) {
      console.log(obj);
      obj.style.backgroundColor = "white";
    }
  </script>
</head>
<body onload="bodyLoad()">
  <form action="#" name="myform">
    <input
      type="text"
      id="myinput"
      name="myinput"
      onfocus="focusFunc()"
      onblur="blurFunc()"
    >

    <br>

    <select name="sel" onchange="selectTag()">
      <option value="A">AA</option>
      <option value="B">BB</option>
      <option value="C">CC</option>
      <option value="D">DD</option>
    </select>

    <br>

    <input
      type="text"
      onmouseover="changeColor(this)"
      onmouseout="changeColor2(this)"
    >

    <br>

    <input type="text">
    <br>
    <input type="text" value="1000" name="money">
  </form>
</body>
</html>

정리

JavaScript 이벤트는 HTML 요소에서 발생하는 동작을 감지하고, 그에 맞는 함수를 실행하기 위해 사용한다.

특히 this를 함께 사용하면 이벤트가 발생한 요소를 직접 제어할 수 있기 때문에, 여러 요소에 같은 함수를 적용할 때 유용하다.

This post is licensed under CC BY 4.0 by the author.