Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Is there a way to detect if a handheld browser is used (iOS/Android phone/tablet)?

I tried this with the goal to make an element half as wide in a browser on a handheld device but it doesn't make a difference.

width: 600px; @media handheld { width: 300px; } 

Can it be done and if so how?

edit: From the referred page in jmaes' answer I used

@media only screen and (max-device-width: 480px).

like image 974
ivavid Avatar asked Feb 18 '13 17:02

ivavid


People also ask

How do I know what type of device is used in HTML?

Instead of using jQuery you can use simple JavaScript to detect it: if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i. test(navigator. userAgent) ) { // some code.. }

What is the best way to detect a mobile device in JavaScript?

To detect if the user is using a mobile device in JavaScript, we can use the userAgent property. This property is part of the navigator object and sent by the browser in HTTP headers. It contains information about the name, version, and platform of the browser.


2 Answers

Update (June 2016): I now try to support touch and mouse input on every resolution, since the device landscape is slowly blurring the lines between what things are and aren't touch devices. iPad Pros are touch-only with the resolution of a 13" laptop. Windows laptops now frequently come with touch screens.

Other similar SO answers (see other answer on this question) might have different ways to try to figure out what sort of device the user is using, but none of them are fool-proof. I encourage you to check those answers out if you absolutely need to try to determine the device.


iPhones, for one, ignore the handheld query (Source). And I wouldn't be surprised if other smartphones do, too, for similar reasons.

The current best way that I use to detect a mobile device is to know its width and use the corresponding media query to catch it. That link there lists some popular ones. A quick Google search would yield you any others you might need, I'm sure.

For more iPhone-specific ones (such as Retina display), check out that first link I posted.

like image 160
jamesplease Avatar answered Sep 28 '22 06:09

jamesplease


Here's how I did it:

@media (pointer:none), (pointer:coarse) { } 

Based on https://stackoverflow.com/a/42835826/1365066

like image 45
GrayFace Avatar answered Sep 28 '22 08:09

GrayFace