Skip to content

Instantly share code, notes, and snippets.

@gregersrygg
Created October 3, 2012 17:52
Show Gist options
  • Save gregersrygg/3828586 to your computer and use it in GitHub Desktop.
Save gregersrygg/3828586 to your computer and use it in GitHub Desktop.
Fix touch event bug in iOS 4 and Android 4.0 when page is scrolled
/* Fix touch event bug in iOS 4 and Android 4.0 when page is scrolled.
* This function will take a touch object (evt.touches[x]) and return
* an object litteral with corrected values for clientX and clientY.
*/
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
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment