Search code examples
javascriptbrowserbrowser-detection

Using Javascript, how can I detect whether the browser is running on a tablet device vs a phone?


I have a web application that is being used by browsers on desktop, tablet and phone. A toolbar (made in HTML) when used on tablet and desktop needs to have buttons that are 16 x 16, and then 48 x 48 on phones. The reason for this, is that 16 x 16 comes up as a good size on the desktop and tablet, but too small on phones (iPhone 4/4s, etc). 48 x 48 is too big on desktop and tablet, but perfect on the phones we've tested.

How can I do the necessary detection for this using Javascript?

I imagine that detecting the physical screen size in inches or millimeters would be a good way to go. Is this possible from within the browser? I've seen some information about detecting screen resolutions in pixels, but to me that seems flawed because the resolution boundaries between phone and tablet are blurring.

What is the most reliable method for detecting a tablet from inside the browser?

We are testing using an iPad 2, Android tablet and the Android Emulator.


Solution

  • Originally I thought that what I needed to know was what kind of device the web application was running on, and then I moved on to thinking that I needed to know the physical screen size of the device. I now think that it is actually the DPI of the device that is relevant.

    On a low resolution device such as a desktop monitor (typically well below 150 DPI) or an iPad 2 (132 DPI), the 16 x 16 buttons is a good size, but on a high resolution device such as an iPhone with retina display (326 DPI), the 48 x 48 buttons are better suited because 16 x6 16 shows up way too small.

    Using Modernizr with it's .mq() function for running media queries, you can determine the device's screen resolution with Javascript code.

    var isHighResolutionDisplay = Modernizr.mq("screen and (-webkit-min-device-pixel-ratio: 2), (min--moz-device-pixel-ratio: 2), (min-resolution: 250dpi)");
    

    This page has a great list of many different devices and their pixel density.