자바스크립트 모바일 터치 이벤트 - jabaseukeulibteu mobail teochi ibenteu

touch event? click event? mouse event?

처음으로 모바일쪽 웹 페이지를 고려하여 개발을 들어가시는 분들은 PC 페이지에서는 이벤트 들이 제대로 실행 되었는데, 모바일에서는 실행되지 않았던 경험을 겪어 보셨을 거에요.

모바일은 이벤트의 종류가 PC 버전과는 상이하기 때문인데, 대표적으로는 touch, click, mouse 세가지가 혼동 되실 것 같아요.

개인적으로 세 이벤트를 이해하기 쉽게 설명해 보면,

  • mouse : 컴퓨터와 연결된 mouse와 관련된 이벤트 들이에요. 마우스의 up, down, move, whell 이벤트 들이 이쪽에 포함 되요.
  • click : touch up & down, mouse up & down 을 묶은 이벤트 에요.
  • touch : display를 touch 했을 때 일어나는 up, down, move 등의 이벤트 들이에요.

즉, mouse 이벤트는 touch 이벤트에 연결이 되지 않는 다는 점!

그렇다면 어떻게 구현 해야 할까요?

touchstart, touchmove, touchend로 이벤트를 연결!

터치 이벤트는 주로 세가지 이벤트를 이용하게 되요.

touchstart, touchmove, touchend 이렇게 세 종류인데,

  • touchstart : up
  • touchmove: move
  • touchend : down

정도로 이해해 주시면 될 것 같아요.

jquery 에서의 사용 방법만 예시로 들어 볼게요!

$(object).on("touchstart", function (e) {
	// ...
})

$(object).on("touchmove", function (e) {
	// ...
})

$(object).on("touchend", function (e) {
	// ...
})

위와 같이 연동을 해주시면 되요.

보통 슬라이드 기능(캐러샐 기능) 등을 구현 할 때 자주 사용 하게 되는데, 이 땐 start와 end 이벤트 만으로도 구현이 가능하고,

손가락을 따라가는 슬라이드 기능을 구현 하려면 move event도 이용 해야 겠지요?

한가지 주의해야 할 점은, touchstart와 touchend의 좌표값 접근 방법이 조금 다르다는 점 입니다.

$(object).on("touchstart", function (e) {
	e.originalEvent.touches[0].pageX
    e.originalEvent.touches[0].pageY
    // e.originalEvent.changedTouches[0] 는 사용 불가!
})

$(object).on("touchmove", function (e) {
	e.originalEvent.touches[0].pageX
    e.originalEvent.touches[0].pageY
    e.originalEvent.changedTouches[0].pageX
    e.originalEvent.changedTouches[0].pageY
    // 둘 다 사용 가능!
})

$(object).on("touchend", function (e) {
    e.originalEvent.changedTouches[0].pageX
    e.originalEvent.changedTouches[0].pageY
	// e.originalEvent.touches[0] 는 사용 불가!
})

각 이벤트별 터치 좌표값의 접근 방법은 위 코드를 참조해 주세요..

touchstart에서 시작 좌표값을 저장하고,

touchend에서 끝 좌표값과 시작 좌표값을 비교해 준다면 터치하면서 움직인 거리 값을 측정하여 다른 이벤트 들을 연동 할 수 있겠죠?

그럼 웹에서 구현한 mouse event들도 쉽게 연동이 가능하시 거에요!

/* =========================== */

[ 개발 환경 설정 ]

개발 툴 : Edit++

개발 언어 : javascript

자바스크립트 모바일 터치 이벤트 - jabaseukeulibteu mobail teochi ibenteu

/* =========================== */

/* =========================== */

[소스 코드]

    <script>

    	/*
    	[JS 요약 설명]
    	1. window.onload : 웹 브라우저 로딩 완료 상태를 확인합니다
    	2. addEventListener : 객체에 특정 이벤트를 등록합니다
    	3. touchstart : 터치 시작을 의미합니다
    	4. touchmove : 터치 이동 상태를 의미합니다
    	5. touchend : 터치 종료 상태를 의미합니다
    	6. 참고 : 드래그앤 드롭 기능 구현 시 body 부분에 스크롤 이벤트를 막아줘야 정상 기능이 수행됩니다    	
    	*/
   	
    	


    	/* [html 최초 로드 및 이벤트 상시 대기 실시] */
    	window.onload = function() {
    		console.log("");
    		console.log("[window onload] : [start]");
    		console.log("");


    		// [터치 등록 이벤트 호출]
    		main();
    	};
    	



    	/* [터치 이벤트 등록 및 터치 상황 확인 함수] */
    	function main(){    		
    		console.log("");
    		console.log("[main] : [start]");    		
    		console.log("");


    		// [특정 객체 터치 이벤트 등록 실시]
    		var id = "one_container";
    		document.getElementById(id).addEventListener("touchstart", handleStart, false);
    		document.getElementById(id).addEventListener("touchmove", handleMove, false);
    		document.getElementById(id).addEventListener("touchend", handleEnd, false);
			

    		// [모바일 : 터치 시작 내부 함수 - (주의) 클릭 이벤트와 겹칠 수 있음]
    		function handleStart(evt) {
    			console.log("");
    			console.log("[main] : [handleStart] : [start]");


    			// body 스크롤 막음 [바디영역에서 스크롤있으면 터치 이벤트 안먹힙니다]
    			BodyScrollDisAble();


    			// 터치한 div id 값 확인 
    			var startId = evt.targetTouches[0].target.id;
    			console.log("[main] : [handleStart] : [ID] : " + startId);    			


    			// 좌표값 확인
    			//var startX = $(this).scrollLeft(); //jquery 방식
    			//var startY = $(this).scrollTop(); //jquery 방식
    			var startX = evt.changedTouches[0].clientX;
    			var startY = evt.changedTouches[0].clientY;
    			console.log("[main] : [handleStart] : [X] : " + startX);
    			console.log("[main] : [handleStart] : [Y] : " + startY);
    			console.log("");
    		};


    		// [모바일 : 터치 이동 내부 함수]
    		function handleMove(evt) {
    			console.log("");		
    			console.log("[main] : [handleMove] : [start]");


    			// body 스크롤 막음 [바디영역에서 스크롤있으면 터치 이벤트 안먹힙니다]
    			BodyScrollDisAble();


    			// 터치한 div id 값 확인 	
    			var moveId = evt.targetTouches[0].target.id;
    			console.log("[main] : [handleMove] : [ID] : " + moveId);


    			// 좌표값 확인
    			// var moveX = $(this).scrollLeft(); //jquery 방식
    			// var moveY = $(this).scrollTop(); //jquery 방식
    			var moveX = evt.changedTouches[0].clientX;
    			var moveY = evt.changedTouches[0].clientY;
    			console.log("[main] : [handleMove] : [X] : " + moveX);
    			console.log("[main] : [handleMove] : [Y] : " + moveY);
    			console.log("");
    		};


    		// [모바일 : 터치 종료 내부 함수] 
    		function handleEnd(evt) {
    			console.log("");
    			console.log("[main] : [handleEnd] : [start]");


    			// 바디 스크롤 허용 
    			BodyScrollAble();


    			// 좌표값 확인 
    			var endX = evt.changedTouches[0].clientX;
    			var endY = evt.changedTouches[0].clientY;
    			console.log("[main] : [handleEnd] : [X] : " + endX);
    			console.log("[main] : [handleEnd] : [Y] : " + endY);
    			console.log("");
    		};

    	};




    	/* [body 영역 스크롤 관리 부분] */
    	function BodyScrollDisAble(){
    		document.body.style.overflow = "hidden"; //스크롤 막음
    	};		
    	function BodyScrollAble(){
    		document.body.style.overflow = "auto"; //스크롤 허용
    	};
    	
    </script>

/* =========================== */

/* =========================== */

[결과 출력]

자바스크립트 모바일 터치 이벤트 - jabaseukeulibteu mobail teochi ibenteu

/* =========================== */

/* =========================== */

[요약 설명]

/*

[JS 요약 설명]

1. window.onload : 웹 브라우저 로딩 완료 상태를 확인합니다

2. addEventListener : 객체에 특정 이벤트를 등록합니다

3. touchstart : 터치 시작을 의미합니다

4. touchmove : 터치 이동 상태를 의미합니다

5. touchend : 터치 종료 상태를 의미합니다

6. 참고 : 드래그앤 드롭 기능 구현 시 body 부분에 스크롤 이벤트를 막아줘야 정상 기능이 수행됩니다

*/

/* =========================== */