4

Is it okay to do the following to determine if you are on mobile device?

if(window.Touch != undefined) 
{
   //redirect to my mobile site
}

I would like to do a small check to see if its a mobile device. I don't want to import modernizr library just for this simple check.

dev.e.loper
  • 35,446
  • 76
  • 161
  • 247

3 Answers3

3

This is what I do and so far it has worked pretty well:

var HAS_TOUCH = ('ontouchstart' in window);
mckamey
  • 17,359
  • 16
  • 83
  • 116
1

I'm using:

if(window.MSPointerEvent){
    //you are on IE10
}else if(window.PointerEvent){
    //you are on IE11
}else if(window.TouchEvent){
    //android and safari
}else{
    //don't have touch events
}

I tested this on Android 2.3 and 4.4.2 and on iOS 7.1. For the IE I used what Microsoft recommended

Using TouchEvent only works if you are on a touch device; that doesn't mean a mobile device. For that use a regular expression on the userAgent:

if(navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i)){
    //you are on Android or iPhone
}

But there are a lot of other cases to treat, for example, Windows Phone and BlackBerry, so I recommend using the detect mobile API.

jiggy
  • 3,828
  • 1
  • 25
  • 40
cel055
  • 11
  • 1
0

Okay found something after extensive search. window.touch doesn't work on Android at least that is what someone has said. I can't confirm since I don't have a mobile device that runs Android

Community
  • 1
  • 1
dev.e.loper
  • 35,446
  • 76
  • 161
  • 247