Touch Event for webkit
touchstart - triggered when a touch is initiated. Mouse equivalent - mouseDowntouchmove - triggered when a touch moves. Mouse equivalent - mouseMove
touchend - triggered when a touch ends. Mouse equivalent - mouseUp.
This one is a bit special on the iPhone - see below
touchcancel - bit of a mystery
Example
docuement.addEventListener('touchstart', function(event) {event.preventDefault();
var touch = event.touches[0];
alert("Touch x:" + touch.pageX + ", y:" + touch.pageY);
}, false);The event object:
- touches - contains touch information upon touchStart and touchMove not touchEnd events
- targetTouches - contains information for touches originating from the same target element
- changedTouches - contains touch information upon all touch events
Example
document.addEventListener('gesturechange', function(event) {event.preventDefault();
alert("Scale: " + event.scale + ", Rotation: " + event.rotation);
}, false);Sometimes you can have trouble when you try to get touch coordinates relative to the
viewpoint of browser from touch event. ClientX/Y properties have offset values including scrolling.
One way of solution you can have is below
function fixTouch (touch) {
var winPageX = window.pageXOffset,
winPageY = window.pageYOffset,
x = touch.clientX,
y = touch.clientY;
if (touch.pageY === 0 && Math.floor(y) > Math.floor(touch.pageY) ||
touch.pageX === 0 && Math.floor(x) > Math.floor(touch.pageX)) {
// iOS4 clientX/clientY have the value that should have been
// in pageX/pageY. While pageX/page/ have the value 0
x = x - winPageX;
y = y - winPageY;
} else if (y < (touch.pageY - winPageY) || x < (touch.pageX - winPageX) ) {
// Some Android browsers have totally bogus values for clientX/Y
// when scrolling/zooming a page. Detectable since clientX/clientY
// should never be smaller than pageX/pageY minus page scroll
x = touch.pageX - winPageX;
y = touch.pageY - winPageY;
}
return { clientX: x, clientY: y };
}Events Table
| tuchstart | 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 | - | - | - |
Comments
Post a Comment