Detect touchscreen devices with JavaScript

There are a lot of ways to detect touchscreen devices with JavaScript. Here are my favorites:

function isTouchDevice(){
  return (typeof(window.ontouchstart) != 'undefined') ? true : false;
}
function isTouchDevice(){
  return ('ontouchstart' in window) ? true : false;
}
function isTouchDevice(){
  return 'ontouchstart' in window;
}

Execution:

if(isTouchDevice())
  alert('Touch me!');
else
  alert('Click me!');

Please note: Windows Phone 7 does not support touch events that’s why you should do this:

function isTouchDevice(){
  if(navigator.userAgent.match('Windows Phone')){
    return true;
  }else{
    return 'ontouchstart' in window;
  }
}

What I also like is the following approach:

if (window.navigator.msPointerEnabled) {
  alert('IE10 / Windows 8 / Touch, pen and mouse');
}
else if('ontouchstart' in window){
  alert('touch device');
}
else{
  alert('mouse device');
}

Prevent scrolling on mobile devices

If you don’t want that the user can scroll your website (to disable the bump-effect on iPhones and iPads for example), then you can use this code snippet which prevents the scrolling on mobile/touch devices:

<script type="text/javascript">
function preventDefaultScrolling(event){
  event.preventDefault();
}
document.ontouchstart = document.ontouchmove = document.ontouchend = preventDefaultScrolling;
</script>

For re-enabling the default scrolling behavior you can do the following:

<script type="text/javascript">
function restoreDefaultScrolling(event){
  return true;
}
document.ontouchstart = document.ontouchmove = document.ontouchend = restoreDefaultScrolling;
</script>

iPad bouncen verhindern

Wer kleine Webseiten auf dem iPad hoch und runter gescrollt hat, wird sicherlich bemerkt haben, dass es dabei einen kleinen „bounce“-Effekt gibt, bei dem über den Rand der Seite hinaus gescrollt werden kann. Dieser Effekt sieht zwar nett aus, ist aber nicht immer wünschenswert.

Um diesen Bounce-Effekt abzuschalten, muss das Standardverhalten bei Touch-Events auf dem iPad verhindert werden. Das geht mit folgendem JavaScript-Schnippsel:

1
2
3
4
document.ontouchmove = function(event)
{
  event.preventDefault();
}

Es gibt übrigens folgende Touch-Events:

  • touchmove
  • touchstart
  • touchend
  • touchcancel