ryandlf
ryandlf

Reputation: 28555

Detecting Mobile vs. Tablet vs. Desktop Javascript

I am running into some issues determining the type of browser using Javascript. My current method is to capture the screen width and height and determine the type of browser based on pixel sizes.

I figured I could assume that any screen width under 768 would be mobile, anything under 1024 tablet, and anything above that a desktop.

I've started testing on a few devices I can actually get my hands on and the results are much different. For instance on an android (Droid Bionic to be exact though it doesn't matter much) its returning a width of 980 regardless if the device is in landscape or portrait mode. This is much higher than I assumed.

Currently I am using document.documentElement.clientWidth to determine the width but I have tried other approaches such as window.innerWidth as well.

I guess what I am trying to get at is a question that has been asked many of times and I thought I had a pretty clear answer to. Apparently it might be time for a refresh on proper browser/device detection. So what is the most effective way to determine the actual size of the device I am on?

UPDATE: It seems as if mobile browsers are actually taking it upon themselves to decide how to display my application. And in fact they are, but there is a way to stop it. See answer. Fortunately this means that the standard feature detection methods we are used to are still the best way to determine the device you are using.

Upvotes: 3

Views: 1848

Answers (1)

ryandlf
ryandlf

Reputation: 28555

Per Dagg Nabbit's comment on the question:

It seems that mobile browsers take it upon themselves to determine the way a site is displayed. This typically means taking a desktop version of a website and zooming out to fit the contents on the screen. For 90% of the internet this is necessary otherwise the mobile browsing experience would be horrifying. For responsive websites this is no good because in most cases we have very specific elements that must be altered depending on the resolution of the device the site is being viewed on. So how do we stop the browsers from doing this?

By using a viewport meta tag. The standard tag looks something like this:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

But there are a lot of different ways you can customize this to suit your needs. A good reference is https://developer.mozilla.org/en-US/docs/Mobile/Viewport_meta_tag

Upvotes: 2

Related Questions