Mobile Geräte erkennen mit JavaScript

Oftmals müssen Webseiten an ein spezifisches Endgerät angepasst werden. Dazu muss man wissen, mit welchem Gerät man es überhaupt zu tun hat. Dabei kann einem die Navigator userAgent Property behilflich sein.
Mobile Geräte erkennen mit JavaScript weiterlesen

Detect Internet Explorer and Google Chrome Frame with JavaScript

To make the Internet Explorer HTML5-competitive it is advisable to install Google Chrome Frame. JavaScript allows to discover whether Google Chrome Frame is already installed.

if(navigator.appName == 'Microsoft Internet Explorer'){
  var hasChromeFrame = navigator.userAgent.match(/(chromeframe)/);
  if(hasChromeFrame == null){
    window.location = 'http://www.google.com/chromeframe';
  }
}

Another option is to use some Google stuff. But then the dialog to install Chrome Frame (CF) is only shown once per session:

<!--[if IE]>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
<script type="text/javascript">
  // Check if Chrome Frame is installed and display an overlay if not
  CFInstall.check({
    mode: "overlay"
  });
</script>
<![endif]-->

How to detect screen orientation change with JavaScript

This is the easiest way to detect if your smartphone (Android, iPhone, …) or tablet device (iPad, Galaxy Tab, …) is in portrait mode or landscape mode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function doOnOrientationChange()
{
  switch(window.orientation) 
  {  
    case -90:
    case 90:
      alert('landscape');
      break; 
    default:
      alert('portrait');
      break; 
  }
}
 
window.onorientationchange = function()
{
  doOnOrientationChange();
};
 
// Initial execution
doOnOrientationChange();

The code also detects if the screen orientation has changed.

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');
}