HTML DOM의 touchmove 이벤트는 사용자가 터치 스크린 위에서 손가락을 누른 상태로 움직일 때 발생하는 이벤트입니다. 모바일 게임이나 드래그 인터랙션을 구현할 때 핵심적으로 활용되는 이벤트로, 터치 지점의 좌표를 실시간으로 추적할 수 있습니다.
참고: touchmove 이벤트는 오직 터치를 지원하는 기기(스마트폰, 태블릿 등)에서만 동작합니다. 일반 데스크톱 환경에서는 마우스 이벤트(mousemove)를 대신 사용해야 합니다.
touchmove 이벤트 문법
HTML에서 직접 트리거하기
ontouchmove = "eventFunction()"
JavaScript에서 트리거하기
eventObject.ontouchmove = eventFunction
참고: 본문의 터치 이벤트 예제는 터치 기능이 있는 모바일 기기 또는 터치스크린 시스템에서 접속한 온라인 HTML 편집기로 실행해야 정상적으로 확인할 수 있습니다. 화면을 2초간 터치하는 것과 같은 실제 터치 조작이 필요하기 때문입니다.
touchmove 이벤트 활용 예제
다음은 touchmove 이벤트를 활용한 간단한 터치 게임 예제입니다. 초록색 안전 구역 안에서 손가락을 움직여 끝까지 도달하면 성공하고, 빨간색 위험 구역에 닿으면 실패하는 방식입니다.
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM touchmove event</title>
<style>
* {
padding: 2px;
margin:5px;
}
form {
width:70%;
margin: 0 auto;
text-align: center;
}
#outer {
width:70%;
margin: 0 auto;
padding: 0;
text-align: center;
border:1px solid black;
height: 105px;
background-color: #28a745;
}
input[type="button"] {
border-radius: 10px;
}
#upper {
border-bottom: 1px solid black;
height: 40px;
margin: 0 0 15px 0;
background-color: #DC3545;
}
#lower {
border-top: 1px solid black;
height: 40px;
margin: 15px 0 0 0;
background-color: #DC3545;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>HTML DOM touchmove event</legend>
<div id="outer">
<div id="upper"><h2>Danger</h2></div>
<div id="lower"><h2>Danger</h2></div>
</div>
<input type="button" id="start" value="Start" onclick="gameStart()">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById('divDisplay');
var gameDisplay = document.getElementById('outer');
function playGame(event) {
var x = event.touches[0].clientX;
var y = event.touches[0].clientY;
if(y > 95 && y < 110){
divDisplay.textContent = 'Keep Going!';
if(x === 439){
divDisplay.textContent = 'Congrats! You Did it!';
gameDisplay.removeEventListener('touchmove', playGame);
}
}
else{
divDisplay.textContent = 'You moved to DANGER area. You loose!';
gameDisplay.removeEventListener('touchmove', playGame);
}
}
function gameStart(){
gameDisplay.addEventListener('touchmove',playGame);
}
</script>
</body>
</html>코드 설명
- gameStart() 함수: 'Start' 버튼을 클릭하면 호출되어 게임 영역(#outer)에 touchmove 이벤트 리스너를 등록합니다.
- playGame() 함수:
event.touches[0].clientX와clientY로 첫 번째 터치 지점의 좌표를 가져옵니다. - y 좌표가 95~110 사이(초록색 안전 구역)에 있으면 "Keep Going!" 메시지를 표시하고, x 좌표가 439에 도달하면 "Congrats! You Did it!"과 함께 이벤트 리스너를 제거합니다.
- 안전 구역을 벗어나 빨간색 위험 구역으로 이동하면 실패 메시지를 출력하고 게임을 종료합니다.
실행 결과
'Start' 버튼을 클릭한 후 커서가 초록색(안전) 구역에 있는 경우:

'Start' 버튼을 클릭한 후 커서가 초록색(안전) 구역 끝에 도달한 경우:

'Start' 버튼을 클릭한 후 커서가 빨간색(위험) 구역에 있는 경우:

이처럼 touchmove 이벤트와 touches 객체의 좌표 정보를 조합하면 터치 위치를 실시간으로 추적하는 다양한 인터랙티브 기능을 손쉽게 구현할 수 있습니다.