JavaScriptJavaScript 기초 · 5기초

이벤트 처리 — 클릭, 입력, 키보드에 반응하기

JavaScript이벤트addEventListenerclickinput

사용자가 무언가를 했을 때 반응하기

웹 페이지에서 사용자는 끊임없이 행동합니다. 버튼을 클릭하고, 텍스트를 입력하고, 마우스를 움직이고, 키를 누릅니다.

이런 사용자 행동을 이벤트(Event) 라 하고, 이에 반응하는 코드를 작성하는 것이 이벤트 처리입니다.


addEventListener 기본 사용법

// 요소.addEventListener("이벤트종류", 실행할함수);
const btn = document.querySelector("#btn");

btn.addEventListener("click", () => {
  console.log("버튼이 클릭됐습니다!");
});

이벤트가 발생할 때마다 두 번째 인자로 넣은 함수가 실행됩니다. 이 함수를 이벤트 핸들러 또는 콜백 함수라고 합니다.


자주 쓰는 이벤트 종류

이벤트발생 시점
click요소를 클릭
dblclick더블 클릭
mouseover마우스가 요소 위로 이동
mouseout마우스가 요소 밖으로 이동
input입력 필드 값이 바뀔 때마다
change입력 필드에서 포커스가 벗어날 때
submit폼 제출 시
keydown키가 눌렸을 때
keyup키에서 손을 뗄 때
load페이지나 이미지 로드 완료
scroll스크롤할 때

이벤트 객체 (event)

이벤트 핸들러는 이벤트 정보를 담은 객체를 받습니다.

const btn = document.querySelector("button");

btn.addEventListener("click", (event) => {
  console.log(event.type);   // "click"
  console.log(event.target); // 클릭된 요소
});

키보드 이벤트

document.addEventListener("keydown", (e) => {
  console.log(e.key);   // 눌린 키 이름 ("Enter", "a", "ArrowUp" 등)

  if (e.key === "Enter") {
    console.log("엔터키를 눌렀습니다!");
  }
});

폼 이벤트

실시간 입력 감지

const input = document.querySelector("#name-input");
const display = document.querySelector("#name-display");

input.addEventListener("input", () => {
  display.textContent = input.value;
});

폼 제출 방지

<form id="my-form">
  <input type="text" id="name-input" placeholder="이름 입력" />
  <button type="submit">제출</button>
</form>
const form = document.querySelector("#my-form");

form.addEventListener("submit", (e) => {
  e.preventDefault();   // 기본 제출 동작(페이지 새로고침) 방지

  const name = document.querySelector("#name-input").value;

  if (name.trim() === "") {
    alert("이름을 입력해주세요.");
    return;
  }

  console.log(`제출된 이름: ${name}`);
});

e.preventDefault()는 폼의 기본 동작(페이지 새로고침)을 막습니다. 거의 모든 폼 처리에서 씁니다.


실전 예제 1: 글자 수 카운터

<textarea id="text-input" placeholder="텍스트를 입력하세요" rows="4"></textarea>
<p>글자 수: <span id="count">0</span></p>
const textarea = document.querySelector("#text-input");
const countDisplay = document.querySelector("#count");

textarea.addEventListener("input", () => {
  countDisplay.textContent = textarea.value.length;
});

실전 예제 2: 색상 변경 버튼

<div id="color-box" style="width:200px; height:200px; background:#ddd;"></div>
<button id="red-btn">빨강</button>
<button id="blue-btn">파랑</button>
<button id="random-btn">랜덤</button>
const box = document.querySelector("#color-box");

document.querySelector("#red-btn").addEventListener("click", () => {
  box.style.backgroundColor = "red";
});

document.querySelector("#blue-btn").addEventListener("click", () => {
  box.style.backgroundColor = "blue";
});

document.querySelector("#random-btn").addEventListener("click", () => {
  const randomColor = `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')}`;
  box.style.backgroundColor = randomColor;
});

이벤트 위임 (Event Delegation)

여러 요소에 각각 이벤트를 붙이는 대신, 부모 요소 하나에 붙여 처리합니다.

<ul id="list">
  <li>항목 1</li>
  <li>항목 2</li>
  <li>항목 3</li>
</ul>
// 각 li에 붙이는 대신
const list = document.querySelector("#list");

list.addEventListener("click", (e) => {
  if (e.target.tagName === "LI") {
    e.target.classList.toggle("selected");
    console.log(e.target.textContent + " 클릭됨");
  }
});

나중에 <li> 가 동적으로 추가돼도 이벤트가 작동합니다.


직접 해보기 ✏️

간단한 할 일 목록(Todo)을 만들어 보세요.

<input type="text" id="todo-input" placeholder="할 일 입력" />
<button id="add-btn">추가</button>
<ul id="todo-list"></ul>

목표:

  1. #add-btn 클릭 시 입력된 텍스트를 <li>#todo-list에 추가
  2. 추가 후 입력 필드 초기화 (input.value = "")
  3. Enter 키로도 추가할 수 있도록

정리

개념코드
이벤트 등록element.addEventListener("click", fn)
이벤트 객체(e) => { e.key, e.target }
폼 기본 동작 방지e.preventDefault()
입력값 가져오기input.value
이벤트 위임부모에서 e.target으로 처리

다음 편에서는 배열 메서드map, filter, find 등 배열을 다루는 강력한 도구를 배웁니다.

궁금한 점이 있으신가요?

협업·의뢰는 아래로, 가벼운 소통은 인스타그램 @bluefox._.hi도 환영이에요.