JavaScript의 터치 이벤트(Touch Events)는 사용자가 스마트폰, 태블릿 등 터치스크린 장치와 상호작용할 때 발생하는 이벤트입니다. 모바일 웹 개발에서 터치 기반 인터랙션을 구현하려면 이러한 이벤트의 동작 방식을 정확히 이해하는 것이 필수적입니다.
주요 터치 이벤트 종류
JavaScript에서 사용할 수 있는 대표적인 터치 이벤트는 다음과 같습니다.
| 이벤트 | 설명 |
|---|---|
| touchstart | 사용자가 터치 표면(화면)에 손가락을 올려 터치 지점이 생성되는 순간 발생합니다. |
| touchmove | 터치 상태에서 손가락이 화면 위를 따라 이동할 때마다 발생합니다. |
| touchend | 손가락을 화면에서 떼어 터치 지점이 사라질 때 발생합니다. |
| touchcancel | 전화 수신 등 외부 요인으로 인해 터치가 강제로 중단되었을 때 발생합니다. |
각 이벤트는 addEventListener() 메서드를 통해 간편하게 등록할 수 있으며, 이벤트 객체에는 touches, targetTouches, changedTouches와 같은 터치 정보가 담겨 있어 멀티터치 처리도 가능합니다.
JavaScript 터치 이벤트 예제 코드
다음은 touchstart 이벤트를 활용한 실제 동작 예제입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result,
.sample {
font-size: 18px;
color: blueviolet;
font-weight: 500;
}
.sample {
color: red;
}
</style>
</head>
<body>
<h1>Touch events in JavaScript</h1>
<div class="sample">Here is some sample text to touch</div>
<div class="result"></div>
<h3>Touch on the above paragraph to make output in the below paragraph visible</h3>
<script>
let resEle = document.querySelector(".result");
let sampleEle = document.querySelector(".sample");
sampleEle.addEventListener("touchstart", () => {
resEle.innerHTML = "Touch start event has been triggered";
});
</script>
</body>
</html>실행 결과
위 코드를 실행하면 다음과 같은 초기 화면이 나타납니다.

빨간색 문구가 있는 영역을 손가락으로 터치하면 touchstart 이벤트 리스너가 호출되어 아래 결과 영역에 다음과 같은 메시지가 출력됩니다.

이처럼 터치 이벤트를 활용하면 모바일 환경에서 스와이프, 드래그, 탭 등 다양한 사용자 인터랙션을 자연스럽게 구현할 수 있습니다.