How to detect a mobile device using jQuery
Asked Answered
U

66

1948

Is there a way to detect whether or not a user is using a mobile device in jQuery? Something similar to the CSS @media attribute? I would like to run a different script if the browser is on a handheld device.

The jQuery $.browser function is not what I am looking for.

Udela answered 18/8, 2010 at 17:22 Comment(17)
Provide a mobile URL specifically for mobile devices. This is how most major sites handle mobile devices. See m.google.com.Seaborne
jQuery does not, and cannot do everything. It is provides cross-browser DOM traversal and manipulation, simple animation and ajax between browsers, and creates a skeleton framework for plugins to build upon. Please be aware of jQuery's limitations before asking specifically for a jQuery solution.Spar
I just noticed that Modernizr supports "CSS3 like" Media Queries: modernizr.com/docs/#mqKirksey
User agents are constantly moving targets, everyone reading this post should be very wary of user agent sniffingBeget
What's a 'mobile' device? Is it a device that supports touch (including Chrome Pixels and Windows 8 laptops with mice)? Is it a device with a small screen (what about retina iPads)? Is it a device with a slow CPU? Or a device with a slow internet connection? Depending on what you want to do the answer to this question will vary. To target screen resolution or touch is easy. If you want to serve up smaller content or less intensive JS for some devices, then there's no silver bullet. Test for window.navigator.connection and fall back to (nasty, bad, ill-advised) userAgent sniffing. My 2 cents.Agent
@DavidGilbertson Why would a slow internet connection make it a mobile device? For all you know, I could be using a satellite internet connection (ex: Google Loon) for my home network.Percaline
@Cole"Cole9"Johnson My point exactly. 'Mobile' seems to be used as an umbrella term for touch, slow CPU, slow network and small screen. But none of these are perfect assumptions. I believe that considering these individually will result in a better product than designing for some vague concept of 'mobile'. Hence me posing that question to the OP.Agent
@DavidGilbertson for me, "mobile" encompasses phones, iPods, and anything that really fits in your pocket. A NetBook (if you remember what those are) isn't "mobile" because you can't fit it in your pocket. It's portable, but it's not mobile.Percaline
@DavidGilbertson I would classify a mobile device as something that isn't meant to function as a fully-featured PC (i.e. Windows, OSX, or countless Linux distros). I know that the line gets rather blurry with Ubuntu Mobile and Linux dual-boots on Android devices, but the distinction is usually most easily made by the OS running on the device (Android isn't a fully featured desktop OS, while Windows 8 is generally not the mobile-oriented one).Lewls
I think that Interaction Media Features are the solution here. (See my answer to this similar question)Plumbism
Related: What's the best way to detect a 'touch screen' device using JavaScript?Posthumous
use cdn https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.js then in your code where you want to check for mobile just use $.browser.mobile it will return true if current device is a mobile. To check for desktop use $.browser.desktopEngadine
Instead of trying to detect a "mobile device", I would try and detect a small screen size. After all, you want to optimize for screen size, right?Diclinous
Let me guess, the problem is not really to detect if user is on mobile or not, but to layout elements on the page? I guess width/height will give the most reliable solutions.Strigil
I have scrolled down on all answers and none of them seems to be good. How is this possible? still no solution ?Tarkington
@DimitriKopriwa TL;DR: let isMobile = /mobi/i.test(navigator.userAgent);Radiolucent
The answer depend greatly of what "mobile" means in your scenario. A small screen? In that case tablets (that are actually mobile devices), will not be detected Running a mobile OS/Browser? In that case, Chromebooks and Desktops running Android = mobile, but devices running GNU/Linux or similar will be not. Have touchscreen? Some notebooks and desktop also have it! Every possible case have exceptions. Decide what you need and go for it.Antiseptic
G
2307

Editor's note: user agent detection is not a recommended technique for modern web apps. See the comments below this answer for confirmation of this fact. It is suggested to use one of the other answers using feature detection and/or media queries.


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..
}

Or you can combine them both to make it more accessible through jQuery...

$.browser.device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));

Now $.browser will return "device" for all above devices

Note: $.browser removed on jQuery v1.9.1. But you can use this by using jQuery migration plugin Code


A more thorough version:

var isMobile = false; //initiate as false
// device detection
if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|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/i.test(navigator.userAgent) 
    || /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.substr(0,4))) { 
    isMobile = true;
}
Gamma answered 18/8, 2010 at 17:22 Comment(6)
Can we use navigator.userAgentData.mobile?Ventre
Nope. It does not work in firefox. UserAgentData is undefined in FF.Millikan
@Ventre would not be the best solution since is not supported on many browsers. You can check this over there: developer.mozilla.org/en-US/docs/Web/API/Navigator/…Tarpan
Please, in 2023, do not try to create separate versions of your website for phones. Instead, use feature detection to determine input mechanism and viewport size. User-Agent sniffing is an awful solution anyway, and not future-proof.Shack
@Shack It's useful to keep this answer here for explaining why historically, this solution has been picked, and, together with its starting note, why this solution is to be avoided, if anybody would later think that this is a good idea. Remove the answer, and you risk having somebody later figure out that this is a great way to engineer their websites. It should be unmarked as the correct answer, though. And please, everyone, upvote the other answers instead.Anybody
@Shack Also; I see you've pasted the same two comments over multiple answers. This is not really helpful. Provide a link to the correct solution instead. Endless scrolling through answers, reading "this is an appalling solution; use feature detection" is not that useful. Where's the answer that explains how to use feature detection? And why exactly are these other answers not sufficient? When do they not work?Anybody
A
661

For me small is beautiful so I'm using this technique:

In CSS file:

/* Smartphones ----------- */
@media only screen and (max-width: 760px) {
  #some-element { display: none; }
}

In jQuery/JavaScript file:

$( document ).ready(function() {      
    var is_mobile = false;

    if( $('#some-element').css('display')=='none') {
        is_mobile = true;       
    }

    // now I can use is_mobile to run javascript conditionally

    if (is_mobile == true) {
        //Conditional script here
    }
 });

My objective was to have my site "mobile-friendly". So I use CSS Media Queries do show/hide elements depending on the screen size.

For example, in my mobile version I don't want to activate the Facebook Like Box, because it loads all those profile images and stuff. And that's not good for mobile visitors. So, besides hiding the container element, I also do this inside the jQuery code block (above):

if(!is_mobile) {
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/pt_PT/all.js#xfbml=1&appId=210731252294735";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
}

You can see it in action at http://lisboaautentica.com

I'm still working on the the mobile version, so it's still not looking as it should, as of writing this.

Update by dekin88

There is a JavaScript API built-in for detecting media. Rather than using the above solution simply use the following:

$(function() {      
    let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;

    if (isMobile) {
        //Conditional script here
    }
 });

Browser Supports: http://caniuse.com/#feat=matchmedia

The advantage of this method is that it's not only simpler and shorter, but you can conditionally target different devices such as smartphones and tablets separately if necessary without having to add any dummy elements into the DOM.

Axle answered 18/8, 2010 at 17:22 Comment(6)
-1 The screen.width property is a global. There's no need to arbitrarily add an element to the DOM and unnecessarily bring in CSS media queries. Plus, if the browser is on a desktop and the user resizes the window, $is_mobile is not going to be updated.Gerardogeratology
Why not: if( screen.width <= 480 ) { // is mobile }Airliner
You've just reinvented window.matchMedia: developer.mozilla.org/en-US/docs/Web/API/Window.matchMediaTactical
The bootstrap/jquery technique is very good if it's put in a function. Just call on screenorientation changed or when size change.Scudo
This breaks in landscape mode (pixel 5, Firefox and Chrome). I suggest editing it like so: window.matchMedia('only screen and ((max-width: 767px) or (max-height: 767px))').matchesSpiel
Please, in 2023, do not try to create separate versions of your website for phones. Instead, use feature detection to determine input mechanism and viewport size. User-Agent sniffing is an awful solution anyway, and not future-proof.Shack
C
295

While Mozilla's Browser detection using the user agent now recommends against this solution:

Note: It's worth re-iterating: it's very rarely a good idea to use user agent sniffing. You can almost always find a better, more broadly compatible way to solve your problem!

it used to recommend:

In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device.

Like this:

if (/Mobi/.test(navigator.userAgent)) {
    // mobile!
}

This will match all common mobile browser user agents, including mobile Mozilla, Safari, IE, Opera, Chrome, etc.

Update for Android

EricL recommends testing for Android as a user agent also, as the Chrome user agent string for tablets does not include "Mobi" (the phone versions do however):

if (/Mobi|Android/i.test(navigator.userAgent)) {
    // mobile!
}
Castora answered 18/8, 2010 at 17:22 Comment(3)
The linked article mentions: 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).Castora
Please, in 2023, do not try to create separate versions of your website for phones. Instead, use feature detection to determine input mechanism and viewport size. User-Agent sniffing is an awful solution anyway, and not future-proof.Shack
If you need to support "Opera Mini" (which hopefully is not the case), then you have to include exactly that in the regex as well, since the user agent contains neither "Mobi" nor "Android".Evocator
F
109

A simple and effective one-liner:

function isMobile() { return ('ontouchstart' in document.documentElement); }

However above code doesn't take into account the case for laptops with touchscreen. Thus, I provide this second version, based on @Julian solution:

function isMobile() {
  try{ document.createEvent("TouchEvent"); return true; }
  catch(e){ return false; }
}
Fuchs answered 18/8, 2010 at 17:22 Comment(3)
What about Windows laptops with touch screen?Crocus
The second isMobile function you provided returns true on my destop device!! (Google Chrome v44.0)Murdocca
This is more of a isTouchSupported method not really mobile detection.Quasar
S
74

It's not jQuery, but I found this: http://detectmobilebrowser.com/

It provides scripts to detect mobile browsers in several languages, one of which is JavaScript. That may help you with what you're looking for.

However, since you are using jQuery, you might want to be aware of the jQuery.support collection. It's a collection of properties for detecting the capabilities of the current browser. Documentation is here: http://api.jquery.com/jQuery.support/

Since I don't know what exactly what you're trying to accomplish, I don't know which of these will be the most useful.

All that being said, I think your best bet is to either redirect or write a different script to the output using a server-side language (if that is an option). Since you don't really know the capabilities of a mobile browser x, doing the detection, and alteration logic on the server side would be the most reliable method. Of course, all of that is a moot point if you can't use a server side language :)

Saccharin answered 18/8, 2010 at 17:22 Comment(1)
There IS a jQuery version there, and it works perfectly, but for tablet detection you must add |android|ipad|playbook|silk as described in the about section (it's by design)Fractocumulus
B
50

Sometimes it is desired to know which brand device a client is using in order to show content specific to that device, like a link to the iPhone store or the Android market. Modernizer is great, but only shows you browser capabilities, like HTML5, or Flash.

Here is my UserAgent solution in jQuery to display a different class for each device type:

/*** sniff the UA of the client and show hidden div's for that device ***/
var customizeForDevice = function(){
    var ua = navigator.userAgent;
    var checker = {
      iphone: ua.match(/(iPhone|iPod|iPad)/),
      blackberry: ua.match(/BlackBerry/),
      android: ua.match(/Android/)
    };
    if (checker.android){
        $('.android-only').show();
    }
    else if (checker.iphone){
        $('.idevice-only').show();
    }
    else if (checker.blackberry){
        $('.berry-only').show();
    }
    else {
        $('.unknown-device').show();
    }
}

This solution is from Graphics Maniacs http://graphicmaniacs.com/note/detecting-iphone-ipod-ipad-android-and-blackberry-browser-with-javascript-and-php/

Bootee answered 18/8, 2010 at 17:22 Comment(0)
B
47

Found a solution in: http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/.

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);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

And then to verify if its a Mobile, you can test using:

if(isMobile.any()) {
   //some code...
}
Bigeye answered 18/8, 2010 at 17:22 Comment(0)
C
32

In one line of javascript:

var isMobile = ('ontouchstart' in document.documentElement && /mobi/i.test(navigator.userAgent));

If the user agent contains 'Mobi' (as per MDN) and ontouchstart is available then it is likely to be a mobile device.

EDIT: Updates the regex code in response to feedback in the comments. Using regex/mobi/i the i makes it case-insensitive, and mobi matches all mobile browsers. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox

Cockadoodledoo answered 18/8, 2010 at 17:22 Comment(0)
P
32

If by "mobile" you mean "small screen," I use this:

var windowWidth = window.screen.width < window.outerWidth ?
                  window.screen.width : window.outerWidth;
var mobile = windowWidth < 500;

On iPhone you'll end up with a window.screen.width of 320. On Android you'll end up with a window.outerWidth of 480 (though that can depend on the Android). iPads and Android tablets will return numbers like 768 so they'll get the full view like you'd want.

Pagandom answered 18/8, 2010 at 17:22 Comment(1)
windowWidth can be set to Math.min(window.screen.width, window.outerWidth) to make it easier to read.Hillock
M
22

I know this question has a lot of answers, but from what I saw nobody approaches the answer the way I would solve this.

CSS uses width (Media Queries) to determine which styles applied to the web document baseed on width. Why not use width in the JavaScript?

For instance in Bootstrap's (Mobile First) Media Queries, there exist 4 snap/break points:

  • Extra Small Devices are 768 pixels and under.
  • Small Devices range from 768 to 991 pixels.
  • Medium Devices range from 992 to 1199 pixels.
  • Large Devices are 1200 pixels and up.

We can use this to also solve our JavaScript issue as well.

First we will create a function that gets the window size and returns a value that allows us to see what size device is viewing our application:

var getBrowserWidth = function(){
    if(window.innerWidth < 768){
        // Extra Small Device
        return "xs";
    } else if(window.innerWidth < 991){
        // Small Device
        return "sm"
    } else if(window.innerWidth < 1199){
        // Medium Device
        return "md"
    } else {
        // Large Device
        return "lg"
    }
};

Now that we have the function set up, we can call it ans store the value:

var device = getBrowserWidth();

Your question was

I would like to run a different script if the browser is on a handheld device.

Now that we have the device information all that is left is an if statement:

if(device === "xs"){
  // Enter your script for handheld devices here 
}

Here is an example on CodePen: http://codepen.io/jacob-king/pen/jWEeWG

Musso answered 18/8, 2010 at 17:22 Comment(2)
This worked best for me. Since I was using bootstrap for some mobile forward pages, this technique worked well to auto redirect away from a non-mobile forward (non-bootstrap) to a bootstrap page. Tip: I found one small problem in IE11 F12 tools: I had emulation turned on in F12 Dev Tools for a mobile device and it had trouble detecting the window size. I had re-sized it below the xs break point but it was detecting it as md. As soon I turned off emulating a phone and refreshed the page, it correctly detected the size and in my code I redirect away to a bootstrap page.Vanegas
@JacobKing you said Small Devices range from 768 to 991 pixels. this means it should be window.innerWidth < 992 (991 is included) the same thing for 1199 it should be < 1200 insteadHarbor
F
19

You can't rely on navigator.userAgent, not every device reveals its real OS. On my HTC for example, it depends on the settings ("using mobile version" on/off). On http://my.clockodo.com, we simply used screen.width to detect small devices. Unfortunately, in some Android versions there's a bug with screen.width. You can combine this way with the userAgent:

if(screen.width < 500 ||
 navigator.userAgent.match(/Android/i) ||
 navigator.userAgent.match(/webOS/i) ||
 navigator.userAgent.match(/iPhone/i) ||
 navigator.userAgent.match(/iPod/i)) {
alert("This is a mobile device");
}
Flout answered 18/8, 2010 at 17:22 Comment(1)
Many mobiles have width of >1000, especially on landscape modeBowlds
M
16

If you use Modernizr, it is very easy to use Modernizr.touch as mentioned earlier.

However, I prefer using a combination of Modernizr.touch and user agent testing, just to be safe.

var deviceAgent = navigator.userAgent.toLowerCase();

var isTouchDevice = Modernizr.touch || 
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/)  || 
deviceAgent.match(/(iemobile)/) || 
deviceAgent.match(/iphone/i) || 
deviceAgent.match(/ipad/i) || 
deviceAgent.match(/ipod/i) || 
deviceAgent.match(/blackberry/i) || 
deviceAgent.match(/bada/i));

if (isTouchDevice) {
        //Do something touchy
    } else {
        //Can't touch this
    }

If you don't use Modernizr, you can simply replace the Modernizr.touch function above with ('ontouchstart' in document.documentElement)

Also note that testing the user agent iemobile will give you broader range of detected Microsoft mobile devices than Windows Phone.

Also see this SO question

Metaphysic answered 18/8, 2010 at 17:22 Comment(3)
And the same in Dart: TouchEvent.supported.Somersomers
('ontouchstart' in window) is an alternative to Modernizr.touch, too, hacks.mozilla.org/2013/04/…Hydrodynamics
You should really use RegEx | instead of many matches. You also don't need the toLowerCase() because you have the i modifier. Here: var isTouchDevice = Modernizr.touch || /iphone|ipod|ipad|android|iemobile|iphone|ipad|ipod|blackberry|bada/i.test(navigator.userAgent);Bowlds
M
14

I am surprised that no one pointed out a nice site: http://detectmobilebrowsers.com/ It has ready made code in different languages for mobile detection (including but not limited to):

  • Apache
  • ASP
  • C#
  • IIS
  • JavaScript
  • NGINX
  • PHP
  • Perl
  • Python
  • Rails

And if you need to detect the tablets as well, just check About section for additional RegEx parameter.

Android tablets, iPads, Kindle Fires and PlayBooks are not detected by design. To add support for tablets, add |android|ipad|playbook|silk to the first regex.

Morgen answered 18/8, 2010 at 17:22 Comment(3)
For me it was working, can you be more specific what code do you use and where seems to be an issue?Morgen
that page is response, of all other responses are copy paste of that pagePar
These are probably not up to date (although I haven't verified that), since when I visited it, the site says: "Regex updated: 1 August 2014".Kuwait
U
12

If found that just checking navigator.userAgent isn't always reliable. Greater reliability can be achieved by also checking navigator.platform. A simple modification to a previous answer seems to work better:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ||
   (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform))) {
    // some code...
}
Undermost answered 18/8, 2010 at 17:22 Comment(0)
H
12

If you're not particularly worried about small displays you could use width/height detection. So that way if width is under a certain size, the mobile site is thrown up. It may not be the perfect way, but it will probably be the easiest to detect for multiple devices. You may need to put in a specific one for the iPhone 4 (large resolution).

Heck answered 18/8, 2010 at 17:22 Comment(0)
O
9

I know it's very old question about this kind of detection.

My solution is based on scroller width (is exist or not).

// this function will check the width of scroller
// if scroller width is 0px it's mobile device

//function ismob() {
    var dv = document.getElementById('divscr');
    var sp=document.getElementById('res');
    if (dv.offsetWidth - dv.clientWidth == 10) {sp.innerHTML='Is mobile'; //return true; 
    } else {
    sp.innerHTML='It is not mobile'; //return false;
    }
//}
<!-- put hidden div on very begining of page -->
<div id="divscr" style="position:fixed;top:0;left:0;width:50px;height:50px;overflow:hidden;overflow-y:scroll;z-index:-1;visibility:hidden;"></div>
<span id="res"></span>
Oram answered 18/8, 2010 at 17:22 Comment(6)
I like this solution, are there any reason why we shouldn't use this?Audiovisual
Absolutely BRILLIANT! And it's totally cross-browser. Thank you! Edit: it's better to check for (dv.offsetWidth - dv.clientWidth) == 0 because the scrollbar gets smaller than 10px if the window is zoomed in, which is the case in most modern laptops with high resolution but small screen (ie. 4k resolution on a 15.6 inch screen)Tameratamerlane
what a unique solution. i havent seen this anywhere else yet. i can see this running into issues whereby the scrollbar is hidden (e.g. ::-webkit-scrollbar { display: none }) has anybody tested that yet?Quiescent
@Quiescent try to set visible scrollbar for div (id="divscr"). I don't use chrome and doesn't want install it just for testing purpose. Anyone?Oram
Great solution! I just removed the need for an existing div: function is_mobile() { var div = document.createElement('div'); div.style.position = 'fixed'; div.style.left = 0; div.style.top = 0; div.style.width = '50px'; div.style.height = '50px'; div.style.overflowY = 'scroll'; document.body.append(div); if (div.offsetWidth - div.clientWidth == 0) { var ret = true; } else { var ret = false; } div.remove(); return ret; }Roofdeck
You are testing overlay scrollbars here, nothing more. They are also active on desktop safari browsers, but will change if you attach a mouse into that device. So not a good marker for desktops...Lallation
N
9

I advise you check out http://wurfl.io/

In a nutshell, if you import a tiny JavaScript 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.is_mobile) {
    //dostuff();
}

This is what you are looking for.

Disclaimer: I work for the company that offers this free service.

Nichol answered 18/8, 2010 at 17:22 Comment(2)
Something isn't right about the Nexus 7. Are you sure you didn't have the Nexus spoof the UA string in the settings? as far as iPad mini is concerned, yes, that's very hard to distinguish from the other iPad, but it was still recognised as an iPad, right? Is it you that downvoted my post?Djambi
No, the ipad mini was detected as a desktop deviceKorean
S
9

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
    mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile','tablet','mobi']; 
    var ua=navigator.userAgent.toLowerCase();
    for (var i in mobile) if (ua.indexOf(mobile[i]) > -1) return true;

    // nothing found.. assume desktop
    return false;
}
Subgenus answered 18/8, 2010 at 17:22 Comment(1)
your assumption based on localStorage is quite interesting, can you provide a range of supported device or browsers that correctly match your script? I'm interested in finding a solution for this question I asked, and trying to detect mobile-tablet browsers can indeed be an interesting workaroundTien
W
9

Great answer thanks. Small improvement to support Windows phone and Zune:

if (navigator.userAgent.match(/Android/i) ||
  navigator.userAgent.match(/webOS/i) ||
  navigator.userAgent.match(/iPhone/i) ||
  navigator.userAgent.match(/iPad/i) ||
  navigator.userAgent.match(/iPod/i) ||
  navigator.userAgent.match(/BlackBerry/) ||
  navigator.userAgent.match(/Windows Phone/i) ||
  navigator.userAgent.match(/ZuneWP7/i)
) {
  // some code
  self.location = "top.htm";
}
Wina answered 18/8, 2010 at 17:22 Comment(2)
I would say this is the simplest (maybe not best) fix if you are trying to handle hover/dragging events for mobile devices. I use something like this to create a "isMobile" boolean that is then checked for every hover/mouseover event. Thats my two cents, anyways. Adding more js libraries or code that requires user interaction doesn't make too much sense to me; correct me if I am wrong though.Zinck
Since you're using regular expressions, actually use them: if (navigator.userAgent.match(/Android|webOS|iPhone|iPad|etc/)){self.location = "top.htm"}Horologist
D
8

You can use media query to be able to handle it easily.

isMobile = function(){
    var isMobile = window.matchMedia("only screen and (max-width: 760px)");
    return isMobile.matches ? true : false
}
Dishwater answered 18/8, 2010 at 17:22 Comment(0)
Y
7

Check out this post, it gives a really nice code snippet for what to do when touch devices are detected or what to do if touchstart event is called:

$(function(){
  if(window.Touch) {
    touch_detect.auto_detected();
  } else {
    document.ontouchstart = touch_detect.surface;
  }
}); // End loaded jQuery
var touch_detect = {
  auto_detected: function(event){
    /* add everything you want to do onLoad here (eg. activating hover controls) */
    alert('this was auto detected');
    activateTouchArea();
  },
  surface: function(event){
    /* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
    alert('this was detected by touching');
    activateTouchArea();
  }
}; // touch_detect
function activateTouchArea(){
  /* make sure our screen doesn't scroll when we move the "touchable area" */
  var element = document.getElementById('element_id');
  element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
  /* modularize preventing the default behavior so we can use it again */
  event.preventDefault();
}
Yod answered 18/8, 2010 at 17:22 Comment(2)
'ontouchstart' in document.documentElement is probably a better test for touch support than window.Touch. Even better, use Modernizr.js (modernizr.com) because have spent a lot of thought trying to get touch detection right. You can see their touch detection code in modernizr.com/downloads/modernizr.js if you view the development code and search on "touch".Ogle
Touch detection has gotten me into trouble, because some new Windows 8 laptops detect as touchscreens in Chrome, leading to odd results.Sheers
E
6

I know this old question and there is a lot of answer but I think this function is simple and will help for detect all mobile, Tablet and computer browser it work like a charm.

function Device_Type() 
{
    var Return_Device; 
    if(/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile|w3c|acs\-|alav|alca|amoi|audi|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd\-|dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg\-c|lg\-d|lg\-g|lge\-|maui|maxo|midp|mits|mmef|mobi|mot\-|moto|mwbp|nec\-|newt|noki|palm|pana|pant|phil|play|port|prox|qwap|sage|sams|sany|sch\-|sec\-|send|seri|sgh\-|shar|sie\-|siem|smal|smar|sony|sph\-|symb|t\-mo|teli|tim\-|tosh|tsm\-|upg1|upsi|vk\-v|voda|wap\-|wapa|wapi|wapp|wapr|webc|winw|winw|xda|xda\-) /i.test(navigator.userAgent))
    {
        if(/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i.test(navigator.userAgent)) 
        {
            Return_Device = 'Tablet';
        }
        else
        {
            Return_Device = 'Mobile';
        }
    }
    else if(/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i.test(navigator.userAgent)) 
    {
        Return_Device = 'Tablet';
    }
    else
    {
        Return_Device = 'Desktop';
    }

    return Return_Device;
}
Echovirus answered 18/8, 2010 at 17:22 Comment(0)
L
6

I would be suggesting to use following combo of strings, to check if device type being used.

As per Mozilla documentation string Mobi is recommended. But, some of the old tablets doesn't return true if only Mobi is used, hence we should use Tablet string too.

Similarly, for being on the safe side iPad and iPhone strings could also be used to check the device type.

Most of the new devices would return true for Mobi string alone.

if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
    // do something
}
Leila answered 18/8, 2010 at 17:22 Comment(1)
I had to add "android" in there to get working on tablets. I'll have to tweak but I like the approach.Evesham
S
6

All answers use user-agent to detect the browser but 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?

Satyriasis answered 18/8, 2010 at 17:22 Comment(3)
Unfortunately, this is not reliable and anyway it returns true on desktop PCs with touchscreens. stucox.com/blog/you-cant-detect-a-touchscreenCorin
Don't forget laptops with touchscreens and full browser experiences. :-)Thirddegree
this may not be the way to go to check whether it's a mobile-device or not but as the name of your function states it's perfect to check for touch-enabled devices. +1 from me ;-)Haemophilia
P
6

Use this:

/**  * jQuery.browser.mobile (http://detectmobilebrowser.com/)  * jQuery.browser.mobile will be true if the browser is a mobile device  **/ (function(a){jQuery.browser.mobile=/android.+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|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|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|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|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|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

Then use this:

if(jQuery.browser.mobile)
{
   console.log('You are using a mobile device!');
}
else
{
   console.log('You are not using a mobile device!');
}
Paprika answered 18/8, 2010 at 17:22 Comment(0)
H
5
<script>
  function checkIsMobile(){
      if(navigator.userAgent.indexOf("Mobile") > 0){
        return true;
      }else{
        return false;
      }
   }
</script>

If you goto any browser and if you try to get navigator.userAgent then we'll be getting the browser information something like following

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36

The same thing if you do in mobile you'll be getting following

Mozilla/5.0 (Linux; Android 8.1.0; Pixel Build/OPP6.171019.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36

Every mobile browser will have useragent with string containing "Mobile" So I'm using above snippet in my code to check whether current user agent is web/mobile. Based on the result I'll be doing required changes.

Hymenium answered 18/8, 2010 at 17:22 Comment(0)
V
5

Simple function based on http://detectmobilebrowser.com/

function isMobile() {
    var a = 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|phone)|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));
}
Vorticella answered 18/8, 2010 at 17:22 Comment(0)
U
5

Here's a function you can use to get a true/false answer as to whether you're running on a mobile browser. Yes, it is browser-sniffing, but sometimes that is exactly what you need.

function is_mobile() {
    var agents = ['android', 'webos', 'iphone', 'ipad', 'blackberry'];
    for(i in agents) {
        if(navigator.userAgent.match('/'+agents[i]+'/i')) {
            return true;
        }
    }
    return false;
}
Unbeatable answered 18/8, 2010 at 17:22 Comment(2)
That will fail to detect many mobile browsers, especially mobile Chrome. It will also probably fail on some of: Opera Mobile, Firefox mobile, Opera Mini, various popular Chinese mobile browsers, etc etc.Ogle
You don't need for for this! +You forgot to create a RegExp. Here's a simpler one: return !!navigator.userAgent.match(new RegExp(agents.join('|'),'i'))Bowlds
G
4

An ES6 solution that uses several detection techniques within a try/catch block

The function consists of creating a "TouchEvent", seeking support for the "ontouchstart" event or even making a query to the mediaQueryList object.

Purposely, some queries that fail will throw a new error because as we are in a try/catch block we can use it as a fall back to consult the user agent.

I have no usage tests and in many cases it can fail as well as point out false positives.

It should not be used for any kind of real validation but, in a general scope for analysis and statistics where the volume of data can "forgive" the lack of precision, it may still be useful.

const isMobile = ((dc, wd) => {
    // get browser "User-Agent" or vendor ... see "opera" property in `window`
    let ua = wd.userAgent || wd.navigator.vendor || wd.opera;
    try {
        /**
         * Creating a touch event ... in modern browsers with touch screens or emulators (but not mobile) does not cause errors.
         * Otherwise, it will create a `DOMException` instance
         */
        dc.createEvent("TouchEvent");

        // check touchStart event
        (('ontouchstart' in wd) || ('ontouchstart' in dc.documentElement) || wd.DocumentTouch && wd.document instanceof DocumentTouch || wd.navigator.maxTouchPoints || wd.navigator.msMaxTouchPoints) ? void(0) : new Error('failed check "ontouchstart" event');

        // check `mediaQueryList` ... pass as modern browsers
        let mQ = wd.matchMedia && matchMedia("(pointer: coarse)");
        // if no have, throw error to use "User-Agent" sniffing test
        if ( !mQ || mQ.media !== "(pointer: coarse)" || !mQ.matches ) {
            throw new Error('failed test `mediaQueryList`');
        }

        // if there are no failures the possibility of the device being mobile is great (but not guaranteed)
        return true;
    } catch(ex) {
        // fall back to User-Agent sniffing
        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/i.test(ua) || /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(ua.substr(0,4));
    }
})(document, window);


// to show result
let container = document.getElementById('result');

container.textContent = isMobile ? 'Yes, your device appears to be mobile' : 'No, your device does not appear to be mobile';
<p id="result"></p>

The regex used to test the user agent is a little old and was available on the website http://mobiledetect.com which is no longer in operation.

Maybe there is a better pattern but, I don't know.


Fonts:


PS:

As there is no way to identify with 100% accuracy neither by checking features, nor by examining the user agent string with regular expressions. The code snippet above should be seen only as: "one more example for this issue", as well as: "not recommended for use in production".

Grimalkin answered 18/8, 2010 at 17:22 Comment(2)
so then what do u suggest using for "real" validation??Quiescent
In CSS4 you can use @media (any-pointer: coarse) or @media (pointer: coarse) to detect touch devices. And in JS you can use matchMedia with the preceding argument. +1. This is generally the right approach.Shack
A
4

How about mobiledetect.net?

Other solutions seem too basic. This is a lightweight PHP class. It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment. You can also benefit from Mobile Detect by using any of the 3rd party plugins available for: WordPress, Drupal, Joomla, Magento, etc.

Aoristic answered 18/8, 2010 at 17:22 Comment(2)
Because the question asked for jQuery?Gula
how accurate is the PHP script? is it any more accurate than detecting on the clients end?Quiescent
P
4

I use this

if(navigator.userAgent.search("mobile")>0 ){
         do something here
}
Penetrating answered 18/8, 2010 at 17:22 Comment(0)
P
3

You could do simple thing very simple like this

(window.screen.width < 700) {
    //The device is a Mobile
} else {
    //The device is a Desktop
}
Phillipphillipe answered 18/8, 2010 at 17:22 Comment(3)
Just because the viewport is < 700 does not make the device mobileSpeculator
@Speculator This is true. However, for our purposes, it actually works better, because we want our javascript to interact correctly with our CSS media queries.Cheerful
Isn't this code supposed to check if it's portrait or landscape? Or just how few pixels in general? Why not if (window.screen.width < window.screen.height) ?Sumikosumma
D
3

Depending on what for you want to detect mobile (meaning this suggestion won't suit everyone's needs), you might be able to achieve a distinction by looking at the onmouseenter-to-onclick millisecond difference, like I described in this answer.

Discotheque answered 18/8, 2010 at 17:22 Comment(1)
In CSS4 you can use @media (any-pointer: coarse) or @media (pointer: coarse) to detect touch devices. And in JS you can use matchMedia with either of the preceding arguments. +1. This is generally the right approach.Shack
P
3

I tried some of the ways and then I decided to fill a list manually and do a simple JS check. And in the end the user has to confirm. Because some checks gave false positive or negative.

var isMobile = false;
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Opera Mobile|Kindle|Windows Phone|PSP|AvantGo|Atomic Web Browser|Blazer|Chrome Mobile|Dolphin|Dolfin|Doris|GO Browser|Jasmine|MicroB|Mobile Firefox|Mobile Safari|Mobile Silk|Motorola Internet Browser|NetFront|NineSky|Nokia Web Browser|Obigo|Openwave Mobile Browser|Palm Pre web browser|Polaris|PS Vita browser|Puffin|QQbrowser|SEMC Browser|Skyfire|Tear|TeaShark|UC Browser|uZard Web|wOSBrowser|Yandex.Browser mobile/i.test(navigator.userAgent) && confirm('Are you on a mobile device?')) isMobile = true;

Now, if you want to use jQuery to set the CSS, you could do the following:

$(document).ready(function() {
  if (isMobile) $('link[type="text/css"]').attr('href', '/mobile.css');
});

Since the borders between mobile and fixed devices become fluent and mobile browers are already powerful, checking width and user confirmation will probably be the best for the future (assuming that width in some cases will still be important). Because touches are already converted into mouse-ups and downs.

And concerning the mobile movability, I suggest you to think about Yoav Barnea's idea:

if(typeof window.orientation !== 'undefined'){...}
Pecoraro answered 18/8, 2010 at 17:22 Comment(1)
Any sort of required user confirmation for something that should be internal and not bother him in any way is a tragic user experience detail.Tawny
C
3

This is my code I'm using in my projects:

function isMobile() {
 try {
    if(/Android|webOS|iPhone|iPad|iPod|pocket|psp|kindle|avantgo|blazer|midori|Tablet|Palm|maemo|plucker|phone|BlackBerry|symbian|IEMobile|mobile|ZuneWP7|Windows Phone|Opera Mini/i.test(navigator.userAgent)) {
     return true;
    };
    return false;
 } catch(e){ console.log("Error in isMobile"); return false; }
}
Cameleer answered 18/8, 2010 at 17:22 Comment(1)
Please use feature detection, not User-Agent sniffing.Shack
E
2

MDN Suggests checking for touchable points available by using Navigator.maxTouchPoints. If > 0 , the device is tappable and most likely a phone or tablet. https://developer.mozilla.org/en-US/docs/Web/API/Navigator/maxTouchPoints

Englert answered 18/8, 2010 at 17:22 Comment(1)
In CSS4 you can use @media (any-pointer: coarse) or @media (pointer: coarse) to detect touch devices. And in JS you can use matchMedia with the preceding argument. +1. This is generally the right approach.Shack
H
2

The following answer was adapted from the answer at https://attacomsian.com/blog/javascript-detect-mobile-device.

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.

With the value of userAgent, we can use a regular expression to test if it contains some keywords or not and then decide the type of the device (mobile, tablet, or desktop). Optionally, you can also combine this test with the width of the current window.

Here is a function that returns the type of device, the user is currently on:

function deviceType() {
    const ua = navigator.userAgent;
    if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
        return "tablet";
    }
    else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
        return "mobile";
    }
    return "desktop";
};
console.log(deviceType());

🔑 Note: The above solution is not always reliable. The value of the userAgent can be easily changed. For example, when we use bots to scrape a website, we can pass a completely different user agent value to hide our identity. It will make it difficult to detect the actual device type.

Hellenhellene answered 18/8, 2010 at 17:22 Comment(0)
H
2

The screen may be on desktop with a small resolution or a mobile with a wide resolution, as so, combining two answers found here in this question

const isMobile = window.matchMedia("only screen and (max-width: 760px)");
if (/Mobi|Tablet|iPad|iPhone/i.test(navigator.userAgent) || isMobile.matches) {
    console.log('is_mobile')
}
Heterozygote answered 18/8, 2010 at 17:22 Comment(1)
If I resize my desktop window to less than 760px wide, this fails.Shack
S
2

Adding:

In some versions of iOS 9.x, Safari does not present the "iPhone" in navigator.userAgent, but show it in navigator.platform.

var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
    if(!isMobile){
        isMobile=/iPhone|iPad|iPod/i.test(navigator.platform);
    }
Steppe answered 18/8, 2010 at 17:22 Comment(1)
That should not matter, because you should be using feature detection rather than User-Agent sniffing.Shack
S
2

This seems to be a comprehensive, modern solution:

https://github.com/matthewhudson/device.js

It detects several platforms, smartphone vs. tablets, and orientation. It also adds classes to the BODY tag so detection takes place only once and you can read what device you're on with a simple series of jQuery hasClass functions.

Check it out...

[DISCLAIMER: I've got nothing to do with the person who wrote it.]

Sop answered 18/8, 2010 at 17:22 Comment(2)
+1 for the small and neat device.js. But I wouldn't exactly call it a "modern solution", at it's core it uses user agent sniffing. I also wouldn't call it "comprehensive", ua-parser on the other hand is.Leatheroid
Please use feature detection, rather than targetting specific devices.Shack
S
2
var device = {
  detect: function(key) {
    if(this['_'+key] === undefined) {
      this['_'+key] = navigator.userAgent.match(new RegExp(key, 'i'));
    }
    return this['_'+key];
  },
  iDevice: function() {
    return this.detect('iPhone') || this.detect('iPod');
  },
  android: function() {
    return this.detect('Android');
  },
  webOS: function() {
    return this.detect('webOS');
  },
  mobile: function() {
    return this.iDevice() || this.android() || this.webOS();
  }
};

I've used something like this in the past. This is similar to a previous response, but it's technically more performant in that it caches the result of the match, especially if the detection is being used in an animation, scroll event, or the like.

Sentimentalism answered 18/8, 2010 at 17:22 Comment(1)
Why would you need to call this code in an animation/scroll event/etc.?Nessus
K
1

I use this solution and it works fine on all devices:

if (typeof window.orientation !== "undefined" || navigator.userAgent.indexOf('IEMobile') !== -1) {
   //is_mobile
}
Killigrew answered 18/8, 2010 at 17:22 Comment(2)
I was considering this but then I thought about when a user requests the desktop site from the chrome menu, this is done through the User-Agent string and would no longer work.Welterweight
window.orientation is unfortunately deprecated now, and its replacement works on desktop too - so no longer useful I'm afraid. :(Mothering
S
1

If by a mobile device you understand a touchable one, then you can determine it by checking existence of touch handlers:

let deviceType = (('ontouchstart' in window)
                 || (navigator.maxTouchPoints > 0)
                 || (navigator.msMaxTouchPoints > 0)
                 ) ? 'touchable' : 'desktop';

jQuery is not needed for it.

Shaunda answered 18/8, 2010 at 17:22 Comment(0)
A
1

User agent strings should not be trusted alone. Solution below will work in all situations.

function isMobile(a) {
  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/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)));
}

and call this function:

isMobile(navigator.userAgent || navigator.vendor || window.opera)
Airfoil answered 18/8, 2010 at 17:22 Comment(2)
is window.opera necessary? what does it do exactly?Quiescent
You already admitted to the pitfall: "User agent strings should not be trusted alone." And yet your answer relies entirely on the User-Agent. Where do you think navigator.vendor and window.opera come from otherwise?Shack
S
1

http://www.w3schools.com/jsref/prop_nav_useragent.asp

Filter by platform name.

Ex:

x = $( window ).width();

platform = navigator.platform;

alert(platform);

if ( (platform != Ipad) || (x < 768) )  {


} 

^^

Skirling answered 18/8, 2010 at 17:22 Comment(0)
E
1
function isDeviceMobile(){
 var isMobile = {
  Android: function() {
      return navigator.userAgent.match(/Android/i) && navigator.userAgent.match(/mobile|Mobile/i);
  },
  BlackBerry: function() {
      return navigator.userAgent.match(/BlackBerry/i)|| navigator.userAgent.match(/BB10; Touch/);
  },
  iOS: function() {
      return navigator.userAgent.match(/iPhone|iPod/i);
  },
  Opera: function() {
      return navigator.userAgent.match(/Opera Mini/i);
  },
  Windows: function() {
      return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/webOS/i) ;
  },
  any: function() {
      return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
  }
};      
 return isMobile.any()
}
Esophagus answered 18/8, 2010 at 17:22 Comment(1)
Please don't use User-Agent sniffing. It is not future-proof and your website will break without you doing anything. Please use feature detection instead.Shack
U
1

You can also detect it like below

$.isIPhone = function(){
    return ((navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1));

};
$.isIPad = function (){
    return (navigator.platform.indexOf("iPad") != -1);
};
$.isAndroidMobile  = function(){
    var ua = navigator.userAgent.toLowerCase();
    return ua.indexOf("android") > -1 && ua.indexOf("mobile");
};
$.isAndroidTablet  = function(){
    var ua = navigator.userAgent.toLowerCase();
    return ua.indexOf("android") > -1 && !(ua.indexOf("mobile"));
};
Upshot answered 18/8, 2010 at 17:22 Comment(1)
Please user feature detection.Shack
C
1

Also I recommend using the tiny JavaScript library Bowser, yes no r. It is based on the navigator.userAgent and quite well tested for all browsers including iPhone, Android etc.

https://github.com/ded/bowser

You can use simply say:

if (bowser.msie && bowser.version <= 6) {
  alert('Hello China');
} else if (bowser.firefox){
  alert('Hello Foxy');
} else if (bowser.chrome){
  alert('Hello Silicon Valley');
} else if (bowser.safari){
  alert('Hello Apple Fan');
} else if(bowser.iphone || bowser.android){
  alert('Hello mobile');
}
Cuttler answered 18/8, 2010 at 17:22 Comment(1)
Please stop recommending this.Shack
M
1

You could also use server side script and set javascript variables from it.

Example in php

download http://code.google.com/p/php-mobile-detect/ and then set javascript variables.

<script>
//set defaults
var device_type = 'desktop';
</script>

<?php
require_once( 'Mobile_Detect.php');
$detect = new Mobile_Detect();
?>

<script>
device_type="<?php echo ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'mobile') : 'desktop'); ?>";
alert( device_type);
</script>
Muckrake answered 18/8, 2010 at 17:22 Comment(1)
The only clue you get server-side is the HTTP User-Agent. That is some random string, and you can't future-proof it. This is fundamentally the wrong approach, and use of this suggested library should be discouraged. Moreover, devices should not be categorized into 'mobile', 'tablet' or 'desktop'. What about a large phone, or a small tablet? Please use feature detection.Shack
I
0

My experience using the mix of methods revealed some tricky issues -- that I solved using the discredited method of looking for "mobi" in the userAgent.

The case: an invitation page with "important" blocks of text (where, when, RSVP), and secondary (venue details). It displays fine on a desktop screen and a 15" lap top. But on a smart phone it is hard to read.

Solution: for "mobile" devices (that fit in your hand) --- increase the font size in the primary blocks, and hide the secondary blocks.

Alas: using width/height measures is misleading. My phone reports about the same as my laptop (~1000 x ~700). Thus using "< 768 pixels" would return the same result. Changing the size of the < threshold won't help! And the div.offsetWidth - div.clientWidth technique didn't help either.

Which is why -- to differentiate between smart phone and laptop -- I had to resort to looking for "mobi" in the user agent :(

The only real solution would be info on the physical size of the device?

Indebted answered 18/8, 2010 at 17:22 Comment(0)
S
0

combining all the methods and checks together to determine if a device is a mobile device with support for internal gyroscope and sensors:

function isMobileDevice() {
  // touch support
  if ($.support.touch) {
    // check screen width
    if (window.innerWidth < 768) {
      // check for jQuery Mobile
      if ($.mobile) {
        // check user agent
        if (navigator.userAgent.match(/Mobile/i)) {
          // check for camera and microphone support
          if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            // check for support for internal sensors and gyro
            if (window.DeviceOrientationEvent && window.DeviceMotionEvent) {
              // if all conditions are met, return true
              return true;
            }
          }
        }
      }
    }
  }
  
  // if any of the conditions are not met, return false
  return false;
}

if (isMobileDevice()) {
  // mobile
} else {
  // desktop
}

this may not work for all mobile devices, can be modified as per needs

Senator answered 18/8, 2010 at 17:22 Comment(0)
P
0

Utilized previously mentioned sequielo solution and added the function for width/height check (to avoid screen rotation mistake). For selecting min/max borders for mobile viewport, I use this resource https://www.mydevice.io/#compare-devices

function isMobile() {
    try{ document.createEvent("TouchEvent"); return true; }
    catch(e){ return false; }
}

function deviceType() {
    var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),screenType;
    if (isMobile()){
        if ((width <= 650 && height <= 900) || (width <= 900 && height <= 650))
            screenType = "Mobile Phone";
        else
            screenType = "Tablet";
    }
    else
        screenType = "Desktop";
  return screenType;
}
Pancreatin answered 18/8, 2010 at 17:22 Comment(2)
is there any reason to try creating a touch event instead of checking if touchstart exists?Quiescent
Many desktops have a touch screen too. And the window can be resized.Shack
J
0

Here is one more suggestion implemented with pure JavaScript (es6)

const detectDeviceType = () =>
    /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
        ? 'Mobile'
        : 'Desktop';

detectDeviceType();
Janellajanelle answered 18/8, 2010 at 17:22 Comment(2)
absolutely no need for arrow-syntax function.Weaner
@Weaner No need for this at all, arrow-syntax or otherwise. User-Agent sniffing is the wrong approach.Shack
T
0

Checkout http://detectmobilebrowsers.com/ which provides you script for detecting mobile device in variety of languages including

JavaScript, jQuery, PHP, JSP, Perl, Python, ASP, C#, ColdFusion and many more

Tonality answered 18/8, 2010 at 17:22 Comment(1)
Please don't. Please use feature detection, rather than detecting specific device types.Shack
S
-1

What is the specific feature of a mobile device that means you want different behaviour?

Is it the input mechanism (touch and virtual keyboard vs mouse and physical keyboard), the smaller screen size, or something else?

For example, in CSS4 you can use @media (any-pointer: coarse) for touch-enabled devices and @media (pointer: coarse) for devices where the primary input is touch (i.e. phones and tablets whether or not an external keyboard is plugged in). CSS4 is mostly fully supported by modern browsers.

In JavaScript, you can use Window.matchMedia() to test for any CSS media query (including those above) as suggested in this SO answer. (I would have hoped for something more native by now, but couldn't find anything.)

Shack answered 18/8, 2010 at 17:22 Comment(0)
S
-1

you need to controll resize

var  is_mobile = false;
        $(window).resize(function() {

            if ($('#mobileNav').css('display') == 'block') {
                is_mobile = true;
            }

            if (is_mobile == true) {

                console.log('is_mobile')
                document.addEventListener(
                    "DOMContentLoaded", () => {
                        new Mmenu("#mainMenu", {
                            "offCanvas": {
                                "position": "right-front"
                            }
                        });
                    }
                );

            }

        }).resize();
Stillman answered 18/8, 2010 at 17:22 Comment(1)
This answer is out of context. The OP does not have an element with ID mobileNav.Shack
O
-1

Ya'll are doing way too much work.

if (window.screen.availWidth <= 425) {
   // do something
}

You can do this on page load through JS. No need to write long string lists to try and catch everything. Whoops, you missed one! Then you have to go back and change it/add it. The more popular phone sizes are about 425 in width or less (in portrait mode), tablets are around 700 ish and anything bigger is likely a laptop, desktop, or other larger device. If you need mobile landscape mode, maybe you should be working in Swift or Android studio and not traditional web coding.

Side note: This may not have been an available solution when it was posted but it works now.

Osuna answered 18/8, 2010 at 17:22 Comment(0)
C
-1

Check the user agent values.

function ismobile(){
   if(/android|webos|iphone|ipad|ipod|blackberry|opera mini|Windows Phone|iemobile|WPDesktop|XBLWP7/i.test(navigator.userAgent.toLowerCase())) {
       return true;
   }
   else
    return false;
}
Concave answered 18/8, 2010 at 17:22 Comment(4)
This is the wrong approach, so we will not be updating your array.Shack
@Shack I don't know who we are and what array updating you are talking about. This works regardless of the OS version.Concave
We is I. Your solution is totally unsustatainable, if you'd care to think about it. You might think it works now, but perhaps you are naieve. Please only post answers where you have a good understanding of the topic in hand. UA strings can be faked, or set via browser tools. They do not tell you what you are looking for. And if you are UA-sniffing, you don't even know what you are looking for yourself.Shack
You put "help updating the array" in your 'answer'. Then said you didn't know "what array updating [I am] talking about". Really?Shack
M
-2

if you use bootstrap, you can add this element to page and check its visibility:

      <div id="mobile-detect" class="d-sm-none d-md-block" > </div>


function is_mobile() {
   if( $('#mobile-detect').css('display')=='none') {
       return true;
   }
   return false
}
Morehead answered 18/8, 2010 at 17:22 Comment(1)
Please don't use a CSS reset stylesheet. It is totally unnecessary in 2023, and makes your successor's job much harder, as they spend ages trying to figure out where some rogue CSS setting is coming from.Shack
P
-2

This is what I do:

function checkMobile() {
  var os = GetOS();
  if (os == "Android OS" || os == "iOS") {
     // do what you wanna do
     return true
  }
}

and to redirect I add location.href="mobile.website.com" and then add this body tag

<body onload="checkMobile()"></body>
Pedestrianize answered 18/8, 2010 at 17:22 Comment(1)
This is incomplete. You are relying on a function that is not included in the answer to do all the work.Energy
E
-2

Just copy the following function and it returns a boolean value. its regex is looks like the marked answer but it is has some difference:

const isMobile = () =>
  /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series([46])0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(
    navigator.userAgent
  ) ||
  /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([ev])w|bumb|bw-([nu])|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do([cp])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-([mpt])|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c([- _agpst])|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac([ \-/])|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja([tv])a|jbro|jemu|jigs|kddi|keji|kgt([ /])|klon|kpt |kwc-|kyo([ck])|le(no|xi)|lg( g|\/([klu])|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([- ov])|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30([02])|n50([025])|n7(0([01])|10)|ne(([cm])-|on|tf|wf|wg|wt)|nok([6i])|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan([adt])|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([-01])|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([im])|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.substr(0, 4)
  );
Ellis answered 18/8, 2010 at 17:22 Comment(1)
Please use feature detection not User-Agent sniffing.Shack
F
-2

I do this for my .NET applications.

In my shared _Layout.cshtml Page, I add this.

@{
    var isMobileDevice = HttpContext.Current.Request.Browser.IsMobileDevice;
}

<html lang="en" class="@((isMobileDevice)?"ismobiledevice":"")">

Then to check on any page in your site (jQuery):

<script>
var isMobile = $('html').hasClass('ismobiledevice');
</script>
Forbid answered 18/8, 2010 at 17:22 Comment(2)
This doesn't relate to jQuery i'm afraidMauk
Nor does it relate to the OP.Shack
S
-3

navigator.userAgentData.mobile returns [true|false]

Silverweed answered 18/8, 2010 at 17:22 Comment(2)
Might be good in future, but for now it's not supported by iOS Safari, among others: developer.mozilla.org/en-US/docs/Web/API/…Audiovisual
@Audiovisual It probably won't be any good in future, as it will likely be abused by lazy 'developers' (based on the evidence of the 'answers' here). It may have a use in detecting a device capable of making phone calls (e.g. for the tel: link). Feature detection is the way to go.Shack
B
-4

Window.matchMedia()

The Window interface's matchMedia() method returns a new MediaQueryList object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query.

Usage notes You can use the returned media query to perform both instantaneous and event-driven checks to see if the document matches the media query.

To perform a one-time, instantaneous check to see if the document matches the media query, look at the value of the matches property, which will be true if the document meets the media query's requirements.

If you need to be kept aware of whether or not the document matches the media query at all times, you can instead watch for the change event to be delivered to the object. There's a good example of this in the article on Window.devicePixelRatio.

let mql = window.matchMedia('(max-width: 767px)');
Beeck answered 18/8, 2010 at 17:22 Comment(1)
+1 for awareness and admitting that it will go pear-shaped if the desktop user resizes their window. Otherwise, a terrible solution.Shack
A
-5

Use this

if( screen.width <= 480 ) { 
    // is mobile 
}
Alyssa answered 18/8, 2010 at 17:22 Comment(1)
...and what happens if I have my desktop browser less than 480 in size? Why 480 anyway. I'd imagine there are phones when in landscape are wider than 480.Gyve
V
-5

If you want to test the user agent, the correct way is to, test the user agent, i.e. test navigator.userAgent.

If the user fakes this they are not due concern. If you test.isUnix() you should not subsequently have to worry if the system is Unix.

As a user changing userAgent is also fine, but you don't expect sites to render properly if you do.

If you wish to provide support for Microsoft browsers you should ensure the first few characters of the content includes and test every page you write.

Bottom line... Always code to the standards. Then hack it until it works in the current version of IE & don't expect it to look good. That's what GitHub does, and they just got given 100 million bucks.

Venenose answered 18/8, 2010 at 17:22 Comment(1)
Please use feature detection, and do not test the User-Agent.Shack

© 2022 - 2024 — McMap. All rights reserved.