I'm looking for a function which return boolean value if user has mobile browser or not.
I know that I can use navigator.userAgent
and write that function by using regex, but user-agents are too various for different platforms. I doubt that match all possible devices would be easy, and I think this problem has been solved before many times so there should be some kind of complete solution for such task.
I was looking at this site, but sadly the script is so cryptic that I have no idea how to use it for my purpose, which is to create a function which return true / false.
Vary: User-Agent
to your response, otherwise caching proxies will store one version and send it to the other kind of browser. But Vary: User-Agent
makes the response uncachable in IE.
Using Regex (from detectmobilebrowsers.com):
Here's a function that uses an insanely long and comprehensive regex which returns a true
or false
value depending on whether or not the user is browsing with a mobile.
window.mobileCheck = function() {
let 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;
};
For those wishing to include tablets in this test (though arguably, you shouldn't), you can use the following function:
window.mobileAndTabletCheck = function() {
let 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|android|ipad|playbook|silk/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;
};
Using navigator.userAgentData
You may also use navigator.userAgentData.mobile
, but userAgentData
is still experimental, so it is not recommended for use in production.
const isMobile = navigator.userAgentData.mobile; //resolves true/false
Compatibility chart for userAgentData
The Original Answer
You can do this by simply running through a list of devices and checking if the useragent
matches anything like so:
function detectMob() {
const toMatch = [
/Android/i,
/webOS/i,
/iPhone/i,
/iPad/i,
/iPod/i,
/BlackBerry/i,
/Windows Phone/i
];
return toMatch.some((toMatchItem) => {
return navigator.userAgent.match(toMatchItem);
});
}
However since you believe that this method is unreliable, You could assume that any device that had a resolution of 800x600 or less was a mobile device too, narrowing your target even more (although these days many mobile devices have much greater resolutions than this)
i.e
function detectMob() {
return ( ( window.innerWidth <= 800 ) && ( window.innerHeight <= 600 ) );
}
Reference:
Detecting Browser and Devices with javascript
How about:
if (typeof screen.orientation !== 'undefined') { ... }
...since smartphones usually support this property and desktop browsers don't. See in MDN.
EDIT 1: As @Gajus pointed out, window.orientation
is now deprecated and shouldn't be used.
EDIT 2: You can use the experimental screen.orientation
instead of the deprecated window.orientation
. See in MDN.
EDIT 3: Changed from window.orientation to screen.orientation
window.orientation
is a deprecated property (developer.mozilla.org/en-US/docs/Web/API/Window/orientation, compat.spec.whatwg.org/#dom-window-orientation) that some mobile browsers choose to support for unknown reasons. Same browsers implement window.screen.orientation
(which is defined in desktop browsers too). I can only assume that window.orientation
is left there for legacy reasons and should therefore not be used in new applications.
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
How to use
if( isMobile.any() ) alert('Mobile');
To check to see if the user is on a specific mobile device:
if( isMobile.iOS() ) alert('iOS');
Ref: http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript
Enhanced version on github : https://github.com/smali-kazmi/detect-mobile-browser
any()
a for...in loop of ORed isMobile
members?
Here is a simple solution from the source of facebook's slingshot
var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
if (isMobile) {
/* your code here */
}
let isMobile=
now
Came here looking for a simple, clean way to detect "touch screens devices", which I class as mobile and tablets. Did not find a clean choice in the current answers but did work out the following which may also help someone.
var touchDevice = ('ontouchstart' in document.documentElement);
Edit: To support desktops with a touch screen and mobiles at the same time you can use the following:
var touchDevice = (navigator.maxTouchPoints || 'ontouchstart' in document.documentElement);
touchstart|end|etc
.
navigator.maxTouchPoints
(no ms
prefix). There is also an MDN article to check.
According to MDN's article on Browser detection using the user agent, it is encouraged to avoid this approach if possible and suggest other avenues such as feature detection.
However, if one must use the user agent as a means to detect if the device is mobile, they suggest:
In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device.
Therefore, this one-liner will suffice:
const isMobileDevice = window.navigator.userAgent.toLowerCase().includes("mobi");
[UPDATE]:
As @zenw0lf suggests in the comments, using a Regular Expression would be better:
const isMobileDevice = /Mobi/i.test(window.navigator.userAgent)
.includes
not sopport by IE-11
Mobile
in the user agent string
If the device is large enough that it's not marked with “Mobi”, you should serve your desktop site (which, as a best practice, should support touch input anyway, as more desktop machines are appearing with touchscreens).
const isMobile = /Mobi/.test(window.navigator.userAgent)
As many have stated, relying on the moving target of the user agent data is problematic. The same can be said for counting on screen size.
My approach is borrowed from a CSS technique to determine if the interface is touch:
Using only javascript (support by all modern browsers), a media query match can easily infer whether the device is mobile.
function isMobile() {
var match = window.matchMedia || window.msMatchMedia;
if(match) {
var mq = match("(pointer:coarse)");
return mq.matches;
}
return false;
}
There's no perfect solution for detecting whether JS code is executed on a mobile browser, but the following two options should work in most cases.
Option 1 : browser sniffing
!function(a){var b=/iPhone/i,c=/iPod/i,d=/iPad/i,e=/(?=.*\bAndroid\b)(?=.*\bMobile\b)/i,f=/Android/i,g=/(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i,h=/(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i,i=/IEMobile/i,j=/(?=.*\bWindows\b)(?=.*\bARM\b)/i,k=/BlackBerry/i,l=/BB10/i,m=/Opera Mini/i,n=/(CriOS|Chrome)(?=.*\bMobile\b)/i,o=/(?=.*\bFirefox\b)(?=.*\bMobile\b)/i,p=new RegExp("(?:Nexus 7|BNTV250|Kindle Fire|Silk|GT-P1000)","i"),q=function(a,b){return a.test(b)},r=function(a){var r=a||navigator.userAgent,s=r.split("[FBAN");return"undefined"!=typeof s[1]&&(r=s[0]),s=r.split("Twitter"),"undefined"!=typeof s[1]&&(r=s[0]),this.apple={phone:q(b,r),ipod:q(c,r),tablet:!q(b,r)&&q(d,r),device:q(b,r)||q(c,r)||q(d,r)},this.amazon={phone:q(g,r),tablet:!q(g,r)&&q(h,r),device:q(g,r)||q(h,r)},this.android={phone:q(g,r)||q(e,r),tablet:!q(g,r)&&!q(e,r)&&(q(h,r)||q(f,r)),device:q(g,r)||q(h,r)||q(e,r)||q(f,r)},this.windows={phone:q(i,r),tablet:q(j,r),device:q(i,r)||q(j,r)},this.other={blackberry:q(k,r),blackberry10:q(l,r),opera:q(m,r),firefox:q(o,r),chrome:q(n,r),device:q(k,r)||q(l,r)||q(m,r)||q(o,r)||q(n,r)},this.seven_inch=q(p,r),this.any=this.apple.device||this.android.device||this.windows.device||this.other.device||this.seven_inch,this.phone=this.apple.phone||this.android.phone||this.windows.phone,this.tablet=this.apple.tablet||this.android.tablet||this.windows.tablet,"undefined"==typeof window?this:void 0},s=function(){var a=new r;return a.Class=r,a};"undefined"!=typeof module&&module.exports&&"undefined"==typeof window?module.exports=r:"undefined"!=typeof module&&module.exports&&"undefined"!=typeof window?module.exports=s():"function"==typeof define&&define.amd?define("isMobile",[],a.isMobile=s()):a.isMobile=s()}(this); alert(isMobile.any ? 'Mobile' : 'Not mobile');
This particular browser sniffing code is that of a library called isMobile.
Option 2 : window.orientation
Test if window.orientation
is defined :
var isMobile = window.orientation > -1; alert(isMobile ? 'Mobile' : 'Not mobile');
Note
Not all touchscreen devices are mobile and vice versa. So, if you want to implement something specifically for touchscreen, you shouldn't test if your browser is run on a mobile device but rather whether the devices has touchscreen support :
var hasTouchscreen = 'ontouchstart' in window; alert(hasTouchscreen ? 'has touchscreen' : 'doesn\'t have touchscreen');
window.orientation
solution, but the docs say it's deprecated! developer.mozilla.org/en-US/docs/Web/API/Window/orientation
Here is a userAgent solution that is more efficent than match...
function _isMobile(){
// if we want a more complete list use this: http://detectmobilebrowsers.com/
// str.test() is more efficent than str.match()
// remember str.test is case sensitive
var isMobile = (/iphone|ipod|android|ie|blackberry|fennec/).test
(navigator.userAgent.toLowerCase());
return isMobile;
}
/iphone|etc/i.test(navigator.userAgent)
Feature detection is much better than trying to figure out which device you are on and very hard to keep up with new devices coming out all the time, a library like Modernizr lets you know if a particular feature is available or not.
To add an extra layer of control I use the HTML5 storage to detect if it is using mobile storage or desktop storage. If the browser does not support storage I have an array of mobile browser names and I compare the user agent with the browsers in the array.
It is pretty simple. Here is the function:
// Used to detect whether the users browser is an mobile browser
function isMobile() {
///<summary>Detecting whether the browser is a mobile browser or desktop browser</summary>
///<returns>A boolean value indicating whether the browser is a mobile browser or not</returns>
if (sessionStorage.desktop) // desktop storage
return false;
else if (localStorage.mobile) // mobile storage
return true;
// alternative
var mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile'];
for (var i in mobile) if (navigator.userAgent.toLowerCase().indexOf(mobile[i].toLowerCase()) > 0) return true;
// nothing found.. assume desktop
return false;
}
sessionStorage.desktop
doesn't exist in either Safari, Chrome, or Firefox (all newest versions at time of post). You get an up-vote though, since your solution goes in a better direction than others. But don't forget to use var mobile =
instead of mobile =
.
How about something like this?
if(
(screen.width <= 640) ||
(window.matchMedia &&
window.matchMedia('only screen and (max-width: 640px)').matches
)
){
// Do the mobile thing
}
screen.width
instead? It seems to me that's more reliable than window.matchMedia
.
A really good way of detecting mobile or tablet devices is by looking if the browser can create a touch event.
Plain JavaScript Code:
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
if (isMobile()) {
# do whatever you wanna do!
}
This worked for me really well, but there may be a problem with laptop devices which include a touchscreen display.
I am not sure if a touchscreen Laptop will get detected as a mobile device because I haven't tested it yet.
don't use this method as window.orientation is now deprecated!!!
function isMobile() {
return (typeof window.orientation !== "undefined") || (navigator.userAgent.indexOf('IEMobile') !== -1);
};
window.orientation
is deprecated. This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
Feature Detection
const isMobile = localStorage.mobile || window.navigator.maxTouchPoints > 1;
WORKS IN CHROME + SAFARI as of 2022-02-07 :: combining feature detections and trying everything in this thread and other sites. The localStorage.mobile works in Chrome mobile; the latter works in Safari mobile. Does not trigger desktop browsers with or w/o the dev-tools open and/or on a mobile simulator. As of writing this, it triggers a real mobile browser but not desktops.
Please consider
I've also tested this on a Lenovo X1 Yoga (keyboard or tablet-mode) on Win10
localStorage.mobile is undefined no matter what When the laptop is in keyboard mode: window.navigator.maxTouchPoints is 1 → isMobile is false When the keyboard is flipped back and the laptop is in tablet-mode: window.navigator.maxTouchPoints is 10 → isMobile is true
localStorage.mobile
is undefined
no matter what. 2) When the laptop is in keyboard mode, window.navigator.maxTouchPoints
is 1
; so isMobile was false
. 3) When the keyboard is flipped back and the laptop is in tablet mode, window.navigator.maxTouchPoints
is 10
; so isMobile was true
. Now the subjective question: Do we consider a tablet or laptop in tablet-mode as mobile? 🤔
Once the element gains focus, you immediately blur it. Bootstrap-datepicker, which is a very popular and well-maintained component with almost 10,000 stars in GitHub, uses this approach:
if (window.navigator.maxTouchPoints || 'ontouchstart' in document) {
this.input.blur();
}
https://github.com/uxsolutions/bootstrap-datepicker
Thanks to Tigger for assistance.
Here is my re-thought solution for the problem. Still not perfect. The only true solution would be if the device manufacturers start to take seriously the "Mobile" and "Tablet" user-agent strings.
window.onload = userAgentDetect;
function userAgentDetect() {
if(window.navigator.userAgent.match(/Mobile/i)
|| window.navigator.userAgent.match(/iPhone/i)
|| window.navigator.userAgent.match(/iPod/i)
|| window.navigator.userAgent.match(/IEMobile/i)
|| window.navigator.userAgent.match(/Windows Phone/i)
|| window.navigator.userAgent.match(/Android/i)
|| window.navigator.userAgent.match(/BlackBerry/i)
|| window.navigator.userAgent.match(/webOS/i)) {
document.body.className += ' mobile';
alert('True - Mobile - ' + navigator.userAgent);
} else {
alert('False - Mobile - ' + navigator.userAgent);
}
if(window.navigator.userAgent.match(/Tablet/i)
|| window.navigator.userAgent.match(/iPad/i)
|| window.navigator.userAgent.match(/Nexus 7/i)
|| window.navigator.userAgent.match(/Nexus 10/i)
|| window.navigator.userAgent.match(/KFAPWI/i)) {
document.body.className -= ' mobile';
document.body.className += ' tablet';
alert('True - Tablet - ' + navigator.userAgent);
} else {
alert('False - Tablet - ' + navigator.userAgent);
}
}
What happens when the Nexus 7 tablet only have the Android UA string? First, the Mobile become true, than later on the Tablet also become true, but Tablet will delete the Mobile UA string from the body tag.
CSS:
body.tablet { background-color: green; }
body.mobile { background-color: red; }
alert
lines added for development. Chrome console can emulate many handheld devices. Test there.
EDIT:
Just don't use this, use feature detection instead. There are so many devices and brands out there that targeting a brand NEVER will be the right solution.
.match(
... hm. RegExp and .test()
is a simpler variant.
Depends on the use case. All mobile devices require a battery. If what you're after is compute power without draining the battery use the Battery Status API:
navigator.getBattery().then(battery => {
battery.charging ? 'charging' : 'not charging';
});
If what you're looking for is presentational use matchMedia
, which returns a Boolean value:
if (window.matchMedia("(min-width: 400px)").matches) {
/* the viewport is at least 400 pixels wide */
} else {
/* the viewport is less than 400 pixels wide */
}
Or combine them for an even better user experience on tablet devices.
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:
if(WURFL.form_factor == "Tablet"){
//dostuff();
}
This is what you are looking for.
Disclaimer: I work for the company that offers this free service. Thanks.
This is just an es6 port of the accepted answer that I'm using in my project. Note that this also includes tablets.
export const isMobile = () => {
const vendor = navigator.userAgent || navigator.vendor || window.opera;
return !!(
/(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|android|ipad|playbook|silk/i.test(
vendor
) ||
/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(
vendor.substr(0, 4)
)
);
};
Here is a less obfuscated version of the answer by Michael Zaporozhets. It also uses a check to build the regular expressions only on the first call. See this answer for the technique used to build the string from an array of regular expressions.
var gRE = null;
var gRE4 = null;
function PlatformIsMobile()
{
var e;
if ( gRE == null )
{
e =
[
/(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|android|ipad|playbook|silk/
];
gRE = new RegExp(
e.map( function( r ) { return r.source } ).join( "|" ), "i"
);
}
if ( gRE4 == null )
{
e =
[
/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\-/
];
gRE4 = new RegExp(
e.map( function( r ) { return r.source } ).join( "|" ), "i"
);
}
var key = navigator.userAgent || navigator.vendor || window.opera;
return gRE.test( key ) ||
gRE4.test( key.substr( 0, 4 ) );
}
IE10+ solution just using matchMedia:
const isMobile = () => window.matchMedia('(max-width: 700px)').matches
isMobile()
returns a boolean
window.matchMedia('mediaString').matches
returns a boolean.
The best must be :
var isMobile = (/Mobile/i.test(navigator.userAgent));
But like like Yoav Barnea says...
// Seem legit
var isMobile = ('DeviceOrientationEvent' in window || 'orientation' in window);
// But with my Chrome on windows, DeviceOrientationEvent == fct()
if (/Windows NT|Macintosh|Mac OS X|Linux/i.test(navigator.userAgent)) isMobile = false;
// My android have "linux" too
if (/Mobile/i.test(navigator.userAgent)) isMobile = true;
After this 3 tests, i hope var isMobile is... ok
Here is he full function
function isMobile(){
return (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|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|phone)|xda|xiino|android|ipad|playbook|silk/i.test(navigator.userAgent||navigator.vendor||window.opera)||/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((navigator.userAgent||navigator.vendor||window.opera).substr(0,4)))
}
jQuery.noConflict();
jQuery(document).ready(function(){
if(isMobile()) alert("Mobile"); else alert("Not Mobile");
});
what about using "window.screen.width" ?
if (window.screen.width < 800) {
// do something
}
or
if($(window).width() < 800) {
//do something
}
I guess this is the best way because there is a new mobile device every day !
(although I think it's not that supported in old browsers, but give it a try :) )
Here's an ECMAScript 6 solution (TypeScript ready)
public isMobile(): boolean {
let check = false;
((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);
return check;
}
if
condition instead of having this whole check
variable?
Note that Most newer-gen mobile devices now have resolutions greater than 600x400. ie, an iPhone 6....
Proof of test: ran the most upvoted and most recent posts here, with an optional check once run like so:
(function(a){
window.isMobile = (/(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)))
})(navigator.userAgent||navigator.vendor||window.opera);
alert("This browser was found to be a % browser.", window.isMobile ? 'mobile' : 'desktop');
Somehow, the following results were returned on the following Browser Apps. Specs: iPhone 6S, iOS 10.3.1.
Safari (latest): Detected it as a mobile.
Chrome (latest): Did not detect it as a mobile.
SO, i then tested the suggestion from Lanti (https://stackoverflow.com/a/31864119/7183483), and it did return the proper results (mobile for all iOS devices, and desktop for my Mac). Therefore, i proceeded to edit it a little since it would fire twice (for both mobile and Tablet). I then noticed when testing on an iPad, that it also returned as a mobile, which makes sense, since the Parameters that Lanti uses check the OS more than anything. Therefore, i simply moved the tablet IF statement inside the mobile check, which would return mobile is the Tablet check was negative, and tablet otherwise. I then added the else clause for the mobile check to return as desktop/laptop, since both qualify, but then noticed that the browser detects CPU and OS brand. So i added what is returned in there as part of else if statement instead. To cap it, I added a cautionary else statement in case nothing was detected. See bellow, will update with a test on a Windows 10 PC soon.
Oh, and i also added a 'debugMode' variable, to easily switch between debug and normal compiling.
Dislaimer: Full credit to Lanti, also that this was not tested on Windows Tablets... which might return desktop/laptop, since the OS is pure Windows. Will check once I find a friend who uses one.
function userAgentDetect() {
let debugMode = true;
if(window.navigator.userAgent.match(/Mobile/i)
|| window.navigator.userAgent.match(/iPhone/i)
|| window.navigator.userAgent.match(/iPod/i)
|| window.navigator.userAgent.match(/IEMobile/i)
|| window.navigator.userAgent.match(/Windows Phone/i)
|| window.navigator.userAgent.match(/Android/i)
|| window.navigator.userAgent.match(/BlackBerry/i)
|| window.navigator.userAgent.match(/webOS/i)) {
if (window.navigator.userAgent.match(/Tablet/i)
|| window.navigator.userAgent.match(/iPad/i)
|| window.navigator.userAgent.match(/Nexus 7/i)
|| window.navigator.userAgent.match(/Nexus 10/i)
|| window.navigator.userAgent.match(/KFAPWI/i)) {
window.deviceTypeVar = 'tablet';
if (debugMode === true) {
alert('Device is a tablet - ' + navigator.userAgent);
}
} else {
if (debugMode === true) {
alert('Device is a smartphone - ' + navigator.userAgent);
};
window.deviceTypeVar = 'smartphone';
}
} else if (window.navigator.userAgent.match(/Intel Mac/i)) {
if (debugMode === true) {
alert('Device is a desktop or laptop- ' + navigator.userAgent);
}
window.deviceTypeVar = 'desktop_or_laptop';
} else if (window.navigator.userAgent.match(/Nexus 7/i)
|| window.navigator.userAgent.match(/Nexus 10/i)
|| window.navigator.userAgent.match(/KFAPWI/i)) {
window.deviceTypeVar = 'tablet';
if (debugMode === true) {
alert('Device is a tablet - ' + navigator.userAgent);
}
} else {
if (debugMode === true) {
alert('Device is unknown- ' + navigator.userAgent);
}
window.deviceTypeVar = 'Unknown';
}
}
I have faced some scenarios where above answers dint work for me. So i came up with this. Might be helpful to someone.
if(/iPhone|iPad|iPod|Android|webOS|BlackBerry|Windows Phone/i.test(navigator.userAgent)
|| screen.availWidth < 480){
//code for mobile
}
It depends on your use case. If you focus on screen use screen.availWidth
, or you can use document.body.clientWidth
if you want to render based on document.
This is what I use. I know userAgent sniffing is frowned upon, but my need happens to be one of the exclusions!
<script>
var brow = navigator.userAgent;
if (/mobi/i.test(brow)) {
alert('Mobile Browser');
// Do something for mobile
} else {
alert('Not on Mobile');
// Do something for non mobile
}
</script>
Ah yes, the age old question...
It really depends on what you want to do in response to the knowledge.
1. Do you want to change UI so it fits nicely on different screen sizes?
Use media queries.
2. Do you want to show/hide things or change functionality based on mouse vs touch?
This answer above will do however there could be cases where a user has both and switches around. In that scenario you can toggle some JS variable and/or add a class to the document body when you detect mouse or touch events
window.addEventListener("mousemove", function () {
isTouch = false;
document.body.classList.add("canHover");
});
window.addEventListener("touchstart", function () {
isTouch = true;
document.body.classList.remove("canHover");
});
body.canHover #aButtonOrSomething:hover {
//css attributes
}
document
.getElementById("aButtonOrSomething")
.addEventListener("mouseover", showTooltip);
document
.getElementById("aButtonOrSomething")
.addEventListener("click", function () {
if (isTouch) showTooltip();
});
3. Do you want to do something specific knowing exactly what device they have?
Success story sharing
|android|ipad|playbook|silk
to the first regex.