자바스크립트의 이벤트 처리
이 글은 자바스크립트의 이벤트 처리에 대해 설명합니다.
YouTube Video
javascript-html-event.html
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>JavaScript & HTML</title>
6 <style>
7 * {
8 box-sizing: border-box;
9 }
10
11 body {
12 margin: 0;
13 padding: 1em;
14 padding-bottom: 10em;
15 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
16 background-color: #f7f9fc;
17 color: #333;
18 line-height: 1.6;
19 }
20
21 .container {
22 max-width: 800px;
23 margin: 0 auto;
24 padding: 1em;
25 background-color: #ffffff;
26 border: 1px solid #ccc;
27 border-radius: 10px;
28 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
29 }
30
31 .container-flex {
32 display: flex;
33 flex-wrap: wrap;
34 gap: 2em;
35 max-width: 1000px;
36 margin: 0 auto;
37 padding: 1em;
38 background-color: #ffffff;
39 border: 1px solid #ccc;
40 border-radius: 10px;
41 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
42 }
43
44 .left-column, .right-column {
45 flex: 1 1 200px;
46 min-width: 200px;
47 }
48
49 h1, h2 {
50 font-size: 1.2rem;
51 color: #007bff;
52 margin-top: 0.5em;
53 margin-bottom: 0.5em;
54 border-left: 5px solid #007bff;
55 padding-left: 0.6em;
56 background-color: #e9f2ff;
57 }
58
59 button {
60 display: block;
61 margin: 1em auto;
62 padding: 0.75em 1.5em;
63 font-size: 1rem;
64 background-color: #007bff;
65 color: white;
66 border: none;
67 border-radius: 6px;
68 cursor: pointer;
69 transition: background-color 0.3s ease;
70 }
71
72 button:hover {
73 background-color: #0056b3;
74 }
75
76 #output {
77 margin-top: 1em;
78 background-color: #1e1e1e;
79 color: #0f0;
80 padding: 1em;
81 border-radius: 8px;
82 min-height: 200px;
83 font-family: Consolas, monospace;
84 font-size: 0.95rem;
85 overflow-y: auto;
86 white-space: pre-wrap;
87 }
88
89 .highlight {
90 outline: 3px solid #ffc107; /* yellow border */
91 background-color: #fff8e1; /* soft yellow background */
92 transition: background-color 0.3s ease, outline 0.3s ease;
93 }
94
95 .active {
96 background-color: #28a745; /* green background */
97 color: #fff;
98 box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
99 transition: background-color 0.3s ease, box-shadow 0.3s ease;
100 }
101 </style>
102</head>
103<body>
104 <div class="container-flex">
105 <div class="left-column">
106 <h2>HTML Sample</h2>
107 <div id="parentDiv">
108 <button id="myButton">Click me</button>
109 </div>
110 </div>
111
112 <div class="right-column">
113 <h2>Form Sample</h2>
114 <form id="myForm">
115 <input type="text" name="username">
116 <button type="submit">Submit</button>
117 </form>
118 </div>
119 </div>
120
121 <div class="container">
122 <h1>JavaScript Console</h1>
123 <button id="executeBtn">Execute</button>
124 <div id="output"></div>
125 </div>
126
127 <script>
128 // Override console.log to display messages in the #output element
129 (function () {
130 const originalLog = console.log;
131 console.log = function (...args) {
132 originalLog.apply(console, args);
133 const output = document.getElementById('output');
134 output.textContent += args.map(String).join(' ') + '\n';
135 };
136 })();
137
138 document.getElementById('executeBtn').addEventListener('click', () => {
139 // Prevent multiple loads
140 if (document.getElementById('externalScript')) return;
141
142 const script = document.createElement('script');
143 script.src = 'javascript-html-event.js';
144 script.id = 'externalScript';
145 //script.onload = () => console.log('javascript-html-event.js loaded and executed.');
146 //script.onerror = () => console.log('Failed to load javascript-html-event.js.');
147 document.body.appendChild(script);
148 });
149 </script>
150</body>
151</html>
자바스크립트의 이벤트 처리
자바스크립트에서 이벤트 처리는 사용자 작업(클릭 및 키보드 입력 등) 또는 브라우저 동작에 반응하여 특정 작업을 실행하는 메커니즘입니다. 이벤트 리스너를 설정하여 동적이고 인터랙티브한 웹 페이지를 만들 수 있습니다.
이벤트 기본 사항
이벤트는 사용자 작업 및 브라우저 동작에 반응하여 발생합니다. 이벤트가 발생하면 관련된 이벤트 핸들러(함수)가 실행됩니다. 예를 들어, 다음과 같은 이벤트가 있습니다:.
- 클릭 (
click
) - 키보드 입력 (
keydown
,keyup
) - 마우스 이동 (
mousemove
,mouseover
) - 폼 제출 (
submit
) - 페이지 로드 완료 (
DOMContentLoaded
) - 스크롤 (
scroll
)
이벤트 리스너 추가하기
이벤트 리스너는 addEventListener()
메서드를 사용하여 설정합니다. 이 메서드는 지정된 이벤트가 발생할 때 특정 함수를 호출합니다.
addEventListener()
의 기본 문법
1element.addEventListener(event, handler);
element
는 이벤트를 감시하는 HTML 요소입니다.event
는 이벤트 이름입니다(예:click
).handler
는 이벤트가 발생할 때 실행되는 함수입니다.
이벤트 객체
이벤트가 발생하면, JavaScript는 이벤트 세부 정보를 포함하는 이벤트 객체를 이벤트 핸들러에 전달합니다. 이 객체에는 어떤 요소가 이벤트를 발생시켰는지와 어떤 키가 눌렸는지 등의 정보가 포함됩니다.
예시: 이벤트 객체 사용하기
1<button id="myButton">Click me</button>
1const button = document.getElementById('myButton');
2
3button.addEventListener('click', (event) => {
4 console.log(event); // Display event details in the console
5 console.log('Clicked element:', event.target); // Display the clicked element
6});
- 이 코드는 버튼을 클릭할 때 이벤트 객체를 사용하여 자세한 정보와 클릭된 요소를 콘솔에 표시합니다.
일반적인 이벤트
클릭 이벤트
click
이벤트는 사용자가 요소를 클릭할 때 발생합니다.
1element.addEventListener('click', () => {
2 console.log('Clicked');
3});
- 이 코드는 요소를 클릭할 때 콘솔에 메시지를 표시합니다.
키보드 이벤트
keydown
및 keyup
이벤트는 사용자가 키를 누르거나 놓을 때 발생합니다. event.key
를 사용하여 어떤 키가 눌렸는지 확인할 수 있습니다.
1document.addEventListener('keydown', (event) => {
2 console.log(`Key pressed: ${event.key}`);
3});
- 이 코드는 사용자가 키를 누를 때 콘솔에 해당 키의 이름을 표시합니다.
마우스 이벤트
mousemove
및 mouseover
이벤트는 마우스 이동 및 호버 시 발생합니다.
1document.addEventListener('mousemove', (event) => {
2 console.log(`Mouse position: X=${event.clientX}, Y=${event.clientY}`);
3});
- 이 코드는 마우스를 움직일 때마다 콘솔에 위치(X, Y 좌표)를 표시합니다.
폼 이벤트
폼 관련 이벤트에는 submit
및 input
이 포함됩니다. submit
이벤트는 폼이 제출될 때 발생하며, 보통 페이지를 다시 로드하게 하지만 event.preventDefault()
를 사용하여 이를 방지할 수 있습니다.
예시: 폼 제출 시 페이지 다시 로드를 방지하기
1<form id="myForm">
2 <input type="text" name="username">
3 <button type="submit">Submit</button>
4</form>
1const form = document.getElementById('myForm');
2
3form.addEventListener('submit', (event) => {
4 event.preventDefault(); // Prevent page reload
5 console.log('Form has been submitted');
6});
- 이 코드는 폼이 제출될 때 페이지가 새로고침되는 것을 방지하고, 대신 콘솔에 메시지를 표시합니다.
이벤트 전파 (버블링과 캡처링)
이벤트는 두 단계로 전파됩니다: 부모 요소에서 자식 요소로 전파되는 캡처 단계와 자식 요소에서 부모 요소로 전파되는 버블링 단계입니다.
이벤트 버블링
기본적으로 이벤트는 가장 안쪽의 요소에서 발생하고 바깥쪽으로 전파됩니다. 이를 버블링이라고 합니다.
예시: 버블링 예제
1<div id="parentDiv">
2 <button id="myButton">Click me</button>
3</div>
1const parent = document.getElementById('parentDiv');
2const button = document.getElementById('myButton');
3
4parent.addEventListener('click', () => {
5 console.log('Parent element was clicked');
6});
7
8button.addEventListener('click', () => {
9 console.log('Button was clicked');
10});
- 이 예제에서 버튼을 클릭하면 버튼의 이벤트가 먼저 발생하고, 그 다음으로 부모 요소의 이벤트가 발생합니다.
이벤트 캡처링
addEventListener()
의 세 번째 인수로 true
를 지정하여 캡처 단계에서 이벤트를 처리할 수 있습니다.
1parent.addEventListener('click', () => {
2 console.log('Capturing: Parent element was clicked');
3}, true);
- 이 코드는 캡처링 단계에서 상위 요소의 클릭 이벤트를 처리하고 콘솔에 메시지를 표시합니다.
stopPropagation()
으로 전파 방지하기
이벤트는 event.stopPropagation()
을 사용하여 전파를 중지할 수 있습니다.
1button.addEventListener('click', (event) => {
2 event.stopPropagation(); // Stop the event propagation
3 console.log('Button was clicked (no propagation)');
4});
- 이 코드는 버튼을 클릭할 때 이벤트가 전파되는 것을 막고 콘솔에 메시지를 표시합니다.
이벤트 제거
removeEventListener()
를 사용하여 이벤트 리스너를 제거할 수 있습니다. 이벤트 리스너를 제거하려면 addEventListener()
에 지정된 함수에 대한 참조가 필요합니다.
1function handleClick() {
2 console.log('Clicked');
3}
4
5const button = document.getElementById('myButton');
6button.addEventListener('click', handleClick);
7button.removeEventListener('click', handleClick); // Remove the event listener
- 이 코드는 버튼에서 클릭 이벤트 리스너를 제거하여 클릭해도 더 이상 처리되지 않도록 합니다.
사용자 정의 이벤트
JavaScript에서는 표준 이벤트 외에도 사용자 정의 이벤트를 생성하고 실행할 수 있습니다. CustomEvent
생성자를 사용하세요.
1document.addEventListener('myCustomEvent', (event) => {
2 console.log(event.detail.message); // Displays "Hello!"
3});
4
5const event = new CustomEvent('myCustomEvent', {
6 detail: {
7 message: 'Hello!'
8 }
9});
10document.dispatchEvent(event);
- 이 코드는 커스텀 이벤트
myCustomEvent
를 생성하고 디스패치하며, 해당 이벤트의 세부 정보를 콘솔에 표시합니다.
요약
이벤트 처리는 웹 애플리케이션의 상호작용성을 높이기 위한 필수 요소입니다. 이벤트 처리의 구성 요소를 활용하면 보다 유연하고 고급스러운 사용자 경험을 제공할 수 있습니다.
- 이벤트 리스너:
addEventListener()
를 사용하여 요소에 이벤트 핸들러를 설정합니다. - 이벤트 객체: 이벤트가 발생하면 이벤트 객체가 전달되며 이를 통해 세부 정보를 얻을 수 있습니다.
- 이벤트 전파: 이벤트는 버블링과 캡처링 두 단계로 전파됩니다.
- 폼 이벤트 및 사용자 정의 이벤트: 폼 제출 이벤트와 사용자 정의 이벤트를 처리할 수 있습니다.
위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.