Gurpreet Singh
Gurpreet Singh

Reputation: 21233

JavaScript tablet detection

Requirement - Detect tablets using JavaScript

I'm not allowed to use any plugin or lib (jQuery is an exception) and want to keep code to minimum.

I have read many posts on this topic and came up with this solution (Checking screen resolution and touch):

var _w = Math.max($(window).width(), $(window).height());
var _h = Math.min($(window).width(), $(window).height());

var tabletView = (_w >= 1000 && _h >= 600);

var is_touch_device = 'ontouchstart' in document.documentElement;

if (tabletView && is_touch_device) {
    alert('tablet');
}
else {
    alert('Not a Tablet');
}​

Question: Is this code reliable enough? If not what's the better approach?

Upvotes: 2

Views: 3152

Answers (1)

Cerbrus
Cerbrus

Reputation: 72957

This will also see phones with larger screen resolutions as tablets.

Other than that, this code is reliable, and there isn't really anything you could do to detect the difference between a phone and tablet, without libraries, or manually parsing user-agents.

Upvotes: 4

Related Questions