Javascript Touch & Gesture Event for Mobile Browser

모바일/JAVAScript& jQuery 2011. 3. 8. 13:04

모바일 브라우저의 Touch, Gesture Event 처리 방법에 대해서 정리해봅니다.
다른 여러 사이트에서 아이폰에대해서는 정리가 많이 되었던데요... 
저는 http://backtothecode.blogspot.com/2009/10/javascript-touch-and-gesture-events.html 이 블로그를 참조하여 아이폰과 안드로이드 폰에 대해서 함께 정리하여 봅니다.


Android and iPhone touch events

Android, iPhone은 공통적으로 터치와 관련해서 다음과 같은 이벤트를 제공합니다. 
  • touchstart - mouseDown 이벤트와 비슷한 이벤트로 손이 화면에 닿으면 발생
  • touchmove - mouseMove 이벤트와 비슷한 이벤트로 손 터치한 상태로 이동하면 발생
  • touchend - mouseUp 이벤트와 비슷한 이벤트로 손을 화면에서 뗄때 발생. 아이폰의 경우 touchcancel 이벤트가발생
  • touchcancel - bit of a mystery 라고 표현하네요. 쬐금 이상하다는...

예제)
document.addEventListener('touchstart', function(event) {
    alert
(event.touches.length);
}, false);

Event object
위의 예제에서 보듯이 Touch Event Object는 touches array를 포함하고 있다.
안드로이드의 경우 이벤트에는 한개의 터치 오브젝트를 포함한다. 즉 touches.length는 1이다.
터치 아이폰의 경우에는 멀티터치가 가능하기 때문에 touches array를 통해서 핸들링 할 수 있다. 
터치 이벤트 객체는 마우스 이벤트 객체와 같이 pageX, pageY 등의 값들을 포함하고 있다.

예제 )
document.addEventListener('touchmove', function(event) {
   
event.preventDefault();
   
var touch = event.touches[0];
    console
.log("Touch x:" + touch.pageX + ", y:" + touch.pageY);
}, false);

  • clientX: X coordinate of touch relative to the viewport (excludes scroll offset)
  • clientY: Y coordinate of touch relative to the viewport (excludes scroll offset)
  • screenX: Relative to the screen
  • screenY: Relative to the screen
  • pageX: Relative to the full page (includes scrolling)
  • pageY: Relative to the full page (includes scrolling)
  • target: Node the touch event originated from
  • identifier: An identifying number, unique to each touch event

iPhone Touch and Gesture Events

애플의 WebKit은 안드로이드와 달리 몇가지 것들을 추가적으로 지원한다. touchEnd 이벤트는 event.touches array에서 현재 touch 를 제거해준다. 대신 event.changeTouches array를 이용해서 볼 수 있다.

애플 iPhone의 터치 이벤트 객체
  • touches - touchStart, touchMove, touchEnd 의 터치 정보를 포함하고 있는 array
  • targetTouches - 같은 target Element로부터 비롯된 touches 정보를 포함
  • changedTouches - 모든 touch 정보를 가지고 있는 객체


Gesture events

애플에서는 pinching, rotating과 같은 멀티 터치 이벤트를 처리할 수 있도록 지원한다.
  • gesturestart - 멀티 터치 시작
  • gesturechange - 멀티 터치를 해서 움직일 때 발생
  • gestureend - 멀티 터치 이벤트가 끝날때 발생
멀티 터치를 위한 이벤트 객체는scale, rotation 값을 갖고 touch 객체가 없다.

예제 )
document.addEventListener('gesturechange', function(event) {
   
event.preventDefault();
    console
.log("Scale: " + event.scale + ", Rotation: " + event.rotation);
}, false);

Event table

touchstart
touchmove
touchend
gesturestart
gesturemove
gestureend
Android
y
y
y
n
n
n
iPhone
y
y
y
y
y
y
has event.touches
y
y
y
n
n
n
(iPhone) has event.scale and event.rotation
n
n
n
y
y
y
(iPhone) touch in event.touches
y
y
n
-
-
-
(iPhone) touch in event.changedTouches
y
y
y
-
-
-




※ 참고 Link :

출처 - http://blog.hometown.co.kr/tag/touchmove
: