Computer Science Mojo

~ David's Notes on coding, software and computer science




Post

How to fix JavaScript 'e.pageX' returning 'nan' on Android

Category: Android     Tag: Android   JavaScript   Web   Mobile  
By: David     On: Sat 05 September 2015      Pageviews: 57

If your JavaScript touch code works perfectly on ios but does nothing on Android, "e.pageX" might be the problem. "e.pageX" simple does not work on Android and returns "not a number", though it works fine both on desktop browsers and ios Safari. Use "e.targetTouches[0].pageX" for Android to fix this problem.

Encountered this problem when making Learn Huge :
"e.targetTouches[0].pageX" is Android specific, so to ensure cross platform compatibility:

1. Check if it's Android or not:

var isAndroid = false;

if( (navigator.userAgent || navigator.vendor || window.opera).match( /Android/i ) ){
    isAndroid = true;
}

2. Use the correct one depending on platform:

if(isAndroid){
    nowX = e.targetTouches[0].pageX - this.offsetLeft;
    nowY = e.targetTouches[0].pageY - this.offsetTop;
}
else{
    nowX = e.pageX - this.offsetLeft;
    nowY = e.pageY - this.offsetTop;
} 

After changing to "e.targetTouches[0].pageX", Android Chrome takes the code happily.