I have been asked to create an actual HTML page / JavaScript to simulate detection of the mobile devices (iPhone / iPad / Android) using JavaScript code. This will then take the user to a different screen which asks them for their email address.
-
if u can know the screen dimensions that way u can differentiate between an iphone and an ipad – lovesh Jul 12 '11 at 15:44
-
1Use can use code : http://stackoverflow.com/questions/11381673/javascript-solution-to-detect-mobile-browser/13819253#13819253 – Mudaser Ali Dec 11 '12 at 11:23
21 Answers
I know this answer is coming 3 years late but none of the other answers are indeed 100% correct. If you would like to detect if the user is on ANY form of mobile device (Android, iOS, BlackBerry, Windows Phone, Kindle, etc.), then you can use the following code:
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
// Take the user to a different screen here.
}

- 1,341
- 11
- 8
-
1
-
3
-
This code snippet helps but the issue with web browser simulated as mobile. Please help – 4302836 Sep 02 '22 at 09:23
You would detect the requesting browsers user agent string, and then decide based on what it is if it's coming from a mobile browser or not. This device is not perfect, and never will be due to the fact that user agents aren't standardized for mobile devices (at least not to my knowledge).
This site will help you create the code: http://www.hand-interactive.com/resources/detect-mobile-javascript.htm
Example:
You could get the user agent in javascript by doing this:
var uagent = navigator.userAgent.toLowerCase();
And then do the check's in the same format as this (just using iPhone as a quick example, but others would need to be a little bit different)
function DetectIphone()
{
if (uagent.search("iphone") > -1)
alert('true');
else
alert('false');
}
Edit
You'd create a simple HTML page like so:
<html>
<head>
<title>Mobile Detection</title>
</head>
<body>
<input type="button" OnClick="DetectIphone()" value="Am I an Iphone?" />
</body>
</html>
<script>
function DetectIphone()
{
var uagent = navigator.userAgent.toLowerCase();
if (uagent.search("iphone") > -1)
alert('true');
else
alert('false');
}
</script>

- 23,528
- 42
- 122
- 184
-
But I am wondering what would be start? Create a dummy webpage and embedd this coding in there. Is it html that we will use in, because as I mentioned in my code above, I have nothing to start with. – Jeevs Jul 12 '11 at 16:04
-
Great!!!! Thanks for that. How about redirecting it to a different page. Do you think something like this would help? if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/Android/i))) { if (document.cookie.indexOf("iphone_redirect=false") == -1) window.location = "http://m.espn.go.com/wireless/?iphone&i=COMR"; – Jeevs Jul 13 '11 at 10:05
-
1Don't forget that user agents can be changed, spoofed and may not reflect the current browser. That being said if a client spoofs/changes their UserAgent and you they the wrong view displayed it's their own fault. There are other ways other than pure user agent although the user agent is typically the root of all detection. There is a really good (although outdated) example here https://github.com/ahand/mobileesp?files=1 – Nico Jul 22 '15 at 13:20
-
A pretty simple solution is to check for the screen width. Since almost all mobile devices have a max screen width of 480px (at present), it's pretty reliable:
if( screen.width <= 480 ) {
location.href = '/mobile.html';
}
The user-agent string is also a place to look. However, the former solution is still better since even if some freaking device does not respond correctly for the user-agent, the screen width doesn't lie.
The only exception here are tablet pc's like the ipad. Those devices have a higher screen width than smartphones and I would probably go with the user-agent-string for those.

- 231,737
- 57
- 305
- 359
-
Right!! I only need to detect iPhone or Android. So this shouldn't be a problem, but just to let you know I have absolutely nothing to start with. Shall I create a dummy Webpage and embedd this! Also how would the detection be checked? Would I need to transfer the script to a phone? – Jeevs Jul 12 '11 at 16:00
-
14
if(navigator.userAgent.match(/iPad/i)){
//code for iPad here
}
if(navigator.userAgent.match(/iPhone/i)){
//code for iPhone here
}
if(navigator.userAgent.match(/Android/i)){
//code for Android here
}
if(navigator.userAgent.match(/BlackBerry/i)){
//code for BlackBerry here
}
if(navigator.userAgent.match(/webOS/i)){
//code for webOS here
}

- 1,674
- 2
- 12
- 12
-
-
2Even though this code won't execute more than one block since it's checking one thing over and over again, this code should make use of else-if blocks because of that reason. Also, what if the user agent variable changes somehow in between blocks? It'll execute more than 1 block, here. – Jake Millington Feb 13 '17 at 22:38
-
You are right ,and don't forget that code was 4 years ago :) and there is now better tools or ways to do the same job – Ahmed Abu Eldahab Feb 14 '17 at 07:38
var isMobileDevice = navigator.userAgent.match(/iPad|iPhone|iPod/i) != null
|| screen.width <= 480;

- 31,774
- 17
- 105
- 99
-
3+1 for regex matching allowing users to easily check for multiple devices in one shot. However, I would add for clarity that because you denote /i at the end of the regex for insensitive match there really is no need to camel case the search params. The following would be equivalent (and also search for android devices): .match(/ipad|iphone|ipod|android/i) – Russ Apr 18 '13 at 18:32
A simple solution could be css-only. You can set styles in your stylesheet, and then adjust them on the bottom of it. Modern smartphones act like they are just 480px wide, while they are actually a lot more. The code to detect a smaller screen in css is
@media handheld, only screen and (max-width: 560px), only screen and (max-device-width: 480px) {
#hoofdcollumn {margin: 10px 5%; width:90%}
}
Hope this helps!

- 518
- 7
- 15
I use mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)

- 1,624
- 2
- 15
- 18
So I did this. Thank you all!
<head>
<script type="text/javascript">
function DetectTheThing()
{
var uagent = navigator.userAgent.toLowerCase();
if (uagent.search("iphone") > -1 || uagent.search("ipad") > -1
|| uagent.search("android") > -1 || uagent.search("blackberry") > -1
|| uagent.search("webos") > -1)
window.location.href ="otherindex.html";
}
</script>
</head>
<body onload="DetectTheThing()">
VIEW NORMAL SITE
</body>
</html>

- 61
- 1
- 4
Since it's now 2015, if you stumbled across this question then you should probably be using window.matchMedia (and, if it's still 2015, polyfilling for older browsers):
if (matchMedia('handheld').matches) {
//...
} else {
//...
}

- 5,453
- 1
- 26
- 32
-
-
2Note from [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/@media) _Note: CSS2.1 and Media Queries 3 defined several additional media types (tty, tv, projection, handheld, braille, embossed, aural), but they were deprecated in Media Queries 4 and shouldn't be used._ – PaulCo Oct 22 '16 at 22:08
-
See my answer below, for some reason handheld doesn't work for me either. – PeterS Mar 15 '19 at 16:18
I advise you check out http://wurfl.io/
In a nutshell, if you import a tiny JS file:
<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>
you will be left with a JSON object that looks like:
{
"complete_device_name":"Google Nexus 7",
"is_mobile":true,
"form_factor":"Tablet"
}
(that's assuming you are using a Nexus 7, of course) and you will be able to do things like:
WURFL.complete_device_name
This is what you are looking for.
Disclaimer: I work for the company that offers this free service. Thanks.

- 1,021
- 8
- 20
-
"You can use these services free of charge, as long as your website is publicly available and does not require fees or paid subscription to access." -https://web.wurfl.io/#wurfl-js – Exel Gamboa May 04 '17 at 15:14
You can use the user-agent string to detect this.
var useragent = navigator.userAgent.toLowerCase();
if( useragent.search("iphone") )
; // iphone
else if( useragent.search("ipod") )
; // ipod
else if( useragent.search("android") )
; // android
etc
You can find a list of useragent strings here http://www.useragentstring.com/pages/useragentstring.php

- 35,812
- 14
- 73
- 140
This is an example of how to check if webpage is loaded in Desktop or mobile app.
JS will execute on page load and you can do Desktop specific things on page load eg hide barcode scanner.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
/*
* Hide Scan button if Page is loaded in Desktop Browser
*/
function hideScanButtonForDesktop() {
if (!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent))) {
// Hide scan button for Desktop
document.getElementById('btnLinkModelScan').style.display = "none";
}
}
//toggle scanButton for Desktop on page load
window.onload = hideScanButtonForDesktop;
</script>
</head>

- 41,955
- 17
- 205
- 154
Testing for user agent is complex, messy and invariably fails. I also didn't find that the media match for "handheld" worked for me. The simplest solution was to detect if the mouse was available. And that can be done like this:
let isMouseAvailable = window.matchMedia("(any-pointer:coarse)").matches;
That will tell you if you need to show hover items or not and anything else that requires a physical pointer. The sizing can then be done on further media queries based on width.
The following little library is a belt braces version of the query above, should cover most "are you a tablet or a phone with no mouse" scenarios.
https://patrickhlauke.github.io/touch/touchscreen-detection/
Media matches have been supported since 2015 and you can check the compatibility here: https://caniuse.com/#search=matchMedia
In short you should maintain variables relating to whether the screen is touch screen and also what size the screen is. In theory I could have a tiny screen on a mouse operated desktop.

- 2,818
- 23
- 36
-
If you're trying to determine whether to show hover items, shouldn't you use the media query `(hover)` instead? – SpoonMeiser Nov 06 '19 at 00:01
-
@SpoonMeiser My point being is that even if the device supports hover, I need a device that can hover. If I don't have a pointer I can't hover. – PeterS Nov 06 '19 at 10:55
-
IIUC hover means that the primary input device supports hover, which a pointer would but a touchscreen wouldn't – SpoonMeiser Nov 06 '19 at 11:00
-
i would suggest code improvement to make it more understandable what you're up to there - 'var result'? what are you testing for? how about 'var isDeviceMobile' or 'var isDeviceDesktop' instead? bcs mouse when present matches 'fine', not 'coarse'. otherwise i think it's a great answer! thank you – okram Jul 25 '22 at 10:31
-
which made me think - can you have a bluetooth mouse working with phone or tablet? or even mouse connected via cable? then i guess this way the detection would fail – okram Jul 25 '22 at 10:39
-
@okram Yes it probably would fail. I see my answer is from 3 years ago and it probably needs revision. You see a lot of variations in controllers such as using an Xbox controller to operate something. I'll make the code improvements anyway. – PeterS Jul 25 '22 at 11:36
Device detection based on user-agent is not very good solution, better is to detect features like touch device (in new jQuery they remove $.browser
and use $.support
instead).
To detect mobile you can check for touch events:
function is_touch_device() {
return 'ontouchstart' in window // works on most browsers
|| 'onmsgesturechange' in window; // works on ie10
}
Taken from What's the best way to detect a 'touch screen' device using JavaScript?
-
Down vote because OP is asking for mobile device. With touchscreen laptops nowadays, 'Touch Device' is not a very good solution. – TheBrenny Feb 24 '15 at 01:33
-
1@thebrenny laptops are mobile devices dude, they can get moved easily from place to place – B''H Bi'ezras -- Boruch Hashem Nov 29 '20 at 20:02
-
Oh boy, I've had some laptops that are pretty useless at being portable! But either way, OP gave iPhone, iPad, and Android as examples for what they wanted to detect, and "mobile" is short for "mobile phone". Probably a better description would've been "keyboardless" – TheBrenny Dec 03 '20 at 04:52
Determine what the User Agent is for the devices that you need to simulate and then test a variable against that.
for example:
// var userAgent = navigator.userAgent.toLowerCase(); // this would actually get the user agent
var userAgent = "iphone"; /* Simulates User Agent for iPhone */
if (userAgent.indexOf('iphone') != -1) {
// some code here
}

- 3,125
- 4
- 32
- 37
The cleanest way of finding device type is:
if (navigator.userAgentData.mobile) { // do something }
(although it isn't yet supported on Safari)
More info: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/mobile

- 11
- 3
-
interesting that this feature is not available on FF even though we have this mdn link. – KuN Feb 23 '22 at 22:13
-
This is my version, quite similar to the upper one, but I think good for reference.
if (mob_url == "") {
lt_url = desk_url;
} else if ((useragent.indexOf("iPhone") != -1 || useragent.indexOf("Android") != -1 || useragent.indexOf("Blackberry") != -1 || useragent.indexOf("Mobile") != -1) && useragent.indexOf("iPad") == -1 && mob_url != "") {
lt_url = mob_url;
} else {
lt_url = desk_url;
}

- 1
- 1
Simply use DeviceDetection
deviceDetection.deviceType // phone | tablet according to device

- 1,230
- 15
- 22
-
Do you work for them? That literally just used user agent – B''H Bi'ezras -- Boruch Hashem Nov 29 '20 at 20:01
Another possibility is to use mobile-detect.js. Try the demo.
Browser usage:
<script src="mobile-detect.js"></script>
<script>
var md = new MobileDetect(window.navigator.userAgent);
// ... see below
</script>
Node.js / Express:
var MobileDetect = require('mobile-detect'),
md = new MobileDetect(req.headers['user-agent']);
// ... see below
Example:
var md = new MobileDetect(
'Mozilla/5.0 (Linux; U; Android 4.0.3; en-in; SonyEricssonMT11i' +
' Build/4.1.A.0.562) AppleWebKit/534.30 (KHTML, like Gecko)' +
' Version/4.0 Mobile Safari/534.30');
// more typically we would instantiate with 'window.navigator.userAgent'
// as user-agent; this string literal is only for better understanding
console.log( md.mobile() ); // 'Sony'
console.log( md.phone() ); // 'Sony'
console.log( md.tablet() ); // null
console.log( md.userAgent() ); // 'Safari'
console.log( md.os() ); // 'AndroidOS'
console.log( md.is('iPhone') ); // false
console.log( md.is('bot') ); // false
console.log( md.version('Webkit') ); // 534.3
console.log( md.versionStr('Build') ); // '4.1.A.0.562'
console.log( md.match('playstation|xbox') ); // false

- 6,075
- 12
- 66
- 96
As I (kind of without success) searched for the proper solution for my hack, I want to add my hack here nonetheless: I simply check for support of device orientation, which seems the most significant diffrence between mobiles and desktop:
var is_handheld=0; // just a global if(window.DeviceOrientationEvent) {is_handheld=1;}
That being said, imho a page should also offer manual choice between mobile / desktop layout. I got 1920*1080 and I can zoom in - an oversimplified and feature-reduced wordpressoid chunk is not always a good thing. Especially forcing a layout based on nonworking device detection - it happens all the time.

- 21
- 4
Similar to several of the answers above. This simple function, works very well for me. It is current as of 2019
function IsMobileCard()
{
var check = false;
(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
return check;
}

- 403
- 3
- 16
-
what is the data source for this insanely long regex that's probably hard to maintain and debug? – okram Jul 25 '22 at 10:32
-