Friday, January 3, 2014

Code: Detecting Mobile Users

A while back, I wrote about how to make a mobile-optimized website. One tip I omitted was the best way to determine what type of user is visiting your site: desktop, mobile or tablet.  The article simply checked the user agent string for "iPod" or "iPhone".

Checking for all kinds of mobile devices (Android and Windows Phone included) and checking for tablets is important. As a new tablet owner (Nexus 10) I am disappointed by the number of sites that insist on sending me to a version of their site that was meant for tiny screens. Undoubtedly, they are seeing "Android" in my user agent string and thinking I'm using a phone.

The desktop version isn't always right for tablets either. Most tablets don't have Flash, so any website with Flash animations should replace those animations with videos, moving gifs, or static images on the tablet version of the site. Additionally, there are ways to make your website optimized for a touchscreen, even if that screen is 7 inches or larger. This is why tablets may deserve their own website version. But in case you don't want or need a tablet version of your website, this article covers the two ways to split up your site.

Mobile (Phone) vs Non-Mobile (Desktop and Tablet)
After much research on the user agent strings of different devices, I discovered there's an easier way to determine whether you're using mobile or not.  You're supposed to detect features, not check the user agent string to determine what device is being used.

var isMobile = (screen.width < 480) || (screen.height < 480);

Even though phones, iPods and other small screen devices have very high resolutions, they are still reporting their heights or widths as less than 480 pixels, depending on the orientation of the device. StackOverflow suggests adding a meta tag and adding a timeout, but the simple code above should do the trick.

Phone vs Tablet vs Desktop
If the device is not mobile/small-screened, then check for the ontouchstart property in the documentElement. Both mobile devices and tablets will have this property that signifies the availability of a touchscreen.

var isMobile = (screen.width < 480) || (screen.height < 480);
var isTouchscreenDevice = 'ontouchstart' in document.documentElement;
var isTablet = !isMobile && isTouchscreenDevice;
var isDesktop = !isMobile && !isTablet;

Exceptions
Some devices are in a grey area in terms of size and functionality. The Samsung Galaxy Note is huge, but still declares itself a "mobile" device. The iPad Mini is 1.8" smaller than the iPad, but its viewport size is the exact same as the iPad. This makes it hard to make a phablet version of your website. There's not much that webmasters can do, except to treat devices how they want to be treated.

No comments:

Post a Comment