Mobile browser sniffing and Screen Orientation detection

Viewport Meta Tag:

You can use the following meta tag which will give a fluid width to the web application. So even if you change the screen orientation it will resize automatically. Works on iPhone and Android, not sure about other devices.

<meta name="viewport" content="width=device-width">

 

Javascript Browser Sniffing:

You can detect a device by sniffing the User Agent string. However it does not work 100% for an iPad because it has ‘iPhone’ string in the User Agent. List of all User Agents by device

You should instead check the navigator.platform Javascript property which will always give the accurate device information.

function isIPad(){
return (navigator.platform.indexOf("iPad") != -1);
}

function isAndroid(){
return (navigator.platform.indexOf("Android") != -1);
}

 

Screen Orientation:

You can use CSS media queries to determine if the device is being held in vertical or horizontal orientation such as:

<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">;

OR

if you want to target styles for specific devices:

## iPad
<link href="ipad.css" rel="stylesheet" media="only screen and (min-device-width: 768px) and (max-device-width: 1024px)" type="text/css" />

## iPhone 3GS
<link href="iphone.css" rel="stylesheet" media="only screen and  (max-device-width: 480px)" type="text/css" />

## iPhone 4
<link href="retnia.css" rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2) and (max-device-width: 480px)" type="text/css" />

 

Mobile Device Feature Detection:

Rather than detecting the current user agent and alter the page presentation based on which browser is running, it is a good practice to perform feature detection. This means that prior to executing code which relies on a browser feature, we test to ensure that the feature works properly.

Following are a few resources that explain how feature detection works:

  1. Feature Detection: State of the Art Browser Scripting
  2. Browser Detection (and What to Do Instead)
  3. Common feature tests

 

 

 Bookmark to delicious Digg this Technorati reddit  

Leave a Comment