how to check if the user touches the device (the smartphone) with javascript

advertisements

I want to build a simple web app that can tell if the user touched the phone (device). Not just the screen, but the all device. So I figure it out how to check if the user touch the screen but not the orientation and motion sensors part. So I found out this code:

if (window.DeviceOrientationEvent) {
  var x = document.getElementById('1');
  var y = document.getElementById('2');
  var z = document.getElementById('3');
  window.addEventListener('deviceorientation', function(eventData) {
        // gamma is the left-to-right tilt in degrees
        console.log(eventData.gamma);
        x.innerHTML = eventData.gamma;
        // beta is the front-to-back tilt in degrees
        console.log(eventData.beta);
        y.innerHTML = eventData.beta;
        // alpha is the compass direction the device is facing in degrees
        console.log(eventData.alpha);
        z.innerHTML = eventData.alpha;
    }, false);
}

And it is showing me a lot of fast-changing data! but when i put down the phone on my table it is keep changing the data like if I was moving my device. So how can I check if the user moves its phone/device? I could not really figure it out, if you could help me with your piece of code and explantion or even show me a site who can I would appreciate it! In a perfect world:

if(user.touchDevice){alert("YOU TOUCHED PHONE!!!");}

Thanks a lot! And sorry for my English :)


You cannot reliably detect touch devices. You can detect browser features like Touch Events API (which can be enabled in browsers on non-touch devices) or assume touch capabilities according to screen size by using media queries (small device will almost always have touch screen).

Please read this article for detailed explanation and possible solutions: http://www.stucox.com/blog/you-cant-detect-a-touchscreen/

This is code which is used by Modernizr to detect "touchevents":

if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
    // Touch events are supported
}

https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js