By superUntitled


2010-08-18 17:22:22 8 Comments

Is there a solid 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.

30 comments

@Victor Juri 2012-02-26 20:57:28

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";
}

@MeanMatt 2012-03-01 00:54:39

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.

@foobarbecue 2019-08-10 22:55:08

Since you're using regular expressions, actually use them: if (navigator.userAgent.match(/Android|webOS|iPhone|iPad|etc/))‌​{self.location = "top.htm"}

@Ron Royston 2019-06-27 20:41:11

Crude, but sufficient for restricting loading larger resources such as video files on phones vs tablet/desktop - simply look for small width or height to cover both orientations. Obviously, if the desktop browser has been resized the below could erroneously detect a phone, but that's fine / close enough for my use case.

Why 480, bcs that's what looks about right based on the info I've found re phone device dimensions.

if(document.body.clientWidth < 480 || document.body.clientHeight < 480) {
  //this is a mobile device
}

@Gonçalo Peres 2012-04-28 14:52:56

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:

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

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

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

The advantage to 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.

@Tom 2012-07-31 09:27:14

Yes this is what I was thinking of as well, and it is great solution. Unfortunately I am working now on project where I need to know exactly what device OS it is and have to use more JS for that... thumbs up for good solution though

@Rimer 2012-09-21 02:26:28

Don't you need #some-element ACTUALLY IN THE DOM for this to work?

@Gonçalo Peres 2012-10-03 14:37:19

Yes Rimer. <div id="some-element"></div> needs to exist in the DOM.

@merv 2012-11-09 15:46:44

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

@Thomas 2013-01-08 17:33:32

I like it... The jQuery should be fired on resize too $(window).resize(function(){ ... }); and the condition I would write if($('#some-element').is(':hidden')){ ... }. Perfect.

@LeGom 2013-01-15 13:15:41

-1 Doesn't work with a galaxy samsung S2

@andrewrjones 2013-01-20 01:05:23

Why not: if( screen.width <= 480 ) { // is mobile }

@Blazemonger 2013-06-14 17:10:06

You could use JavaScript to add the (empty) element to the end of the body, just before testing. Then you wouldn't have to worry about whether every document has it in the HTML. On the other hand, it would be even easier to just test if ($(window).width() <= 760)

@Cole Johnson 2013-08-19 02:18:31

@andrewrjones Retina devices double the width attribute value IIRC. Therefore, a retina iPhone will have a width of 640 and a height of 960 in portrait, and a width of 960 and a height of 640 in landscape.

@Alex W 2013-08-19 19:18:54

Media queries using *-width are the same as testing document.documentElement.clientWidth in JavaScript. *-device-width would be screen.width

@Paul Irish 2014-02-26 19:27:08

You've just reinvented window.matchMedia: developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia

@Diego Plentz 2014-03-04 17:50:25

-1 There's a lot of mobile devices already that are full hd(1920x1080)

@Fabio Napodano 2014-04-21 10:40:57

This doesn't seem to work with BlackBerry because it doesn't support media queries

@Torin Finnemann 2014-04-28 10:48:08

I like this (orginal, pre-edit) solution, "asking" an (possibly creating it temporarily) element of a css property to know whether my layout is in "mobile mode", because I avoid redundantly writing and maintaining media-queries between css and javascript.

@peterincumbria 2014-05-11 08:11:28

Sorry this solution does not work, even adding a listener. Android Galaxy Ace. So better not to use it.

@AGamePlayer 2014-06-29 04:31:55

in the CSS media query max-width: 760px -> Why use the number 760?

@mykola.rykov 2014-07-24 17:46:14

@PaulIrish window.matchMedia is not working in IE < 10 and IE Mobile

@Tommix 2014-10-28 13:41:42

There are FullHD phones and your code is just useless. Resolution is not the most important thing to keep in mind for phones. Lets say jQuery datePicker doesnt work on phones even if res is ok.

@SearchForKnowledge 2014-12-04 14:17:23

I can just minimize my desktop browser to that size, does that mean it is mobile? No!

@kyle.stearns 2015-01-06 17:37:05

For me, this has been a very difficult battle. The determination between phone, tablet, and desktop. Because the viewport width on a desktop can be changed to be the width of a mobile device, and back to full size. One problem with @andrewrjones solution of using if( screen.width <= 480 ) { // is mobile } is that the specified pixel value in a CSS media query does not match the value returned from screen.width. This is because screen.width does not include the scrollbar width, but the CSS media query does. I strongly dislike UA sniffing, but it's provided a reliable solution thus far.

@cregox 2015-05-04 19:55:39

@andrewrjones (and merv) if you are already using css to control which width should be used for be considered "mobile" then there's no reason to add another redundant parameter in javascript. design decision should go on css so I think this is a better approach.

@Ruchira 2016-04-06 04:35:20

@PaulIrish: window.matchMedia is not reliable AFAIK. It's still a working draft and would not work in legacy browsers. I wouldn't rely on that.

@Nam G VU 2016-08-17 07:48:55

Lovely with the solution using window.matchMedia() - that's my accepted answer <3

@Marcelo Rocha 2016-10-18 22:45:51

Not good, for example i need to avoid some video to load if i'm on a mobile device. Simply hide the element won't solve the problem, will load but not how.

@FlyingCactus 2017-07-13 15:43:31

Nice solution, I wanted to mention one addition to using window.matchMedia. It does return an object, so if you're looking for a boolean to use the matches field works great!

@statosdotcom 2018-03-18 04:53:46

Your solution seems elegant, but I would not call the loading of all that jQuery library as something small and beautiful.

@Kevyn Tuleu Dourado 2019-02-18 07:42:40

puts the last answer first please? I read everything and arrived at the end almost jumped for joy xD

@Sjeiti 2019-03-22 10:29:12

If you are going to use matchMedia you really should check for max-device-width and not max-width. Orientation comes into play as well (width becoming height in landscape) so a better solutions would be: window.matchMedia(`(max-device-${window.matchMedia('(orienta‌​tion: portrait)').matches?'width':'height'}: ${411}px)`).matches (where 411 is a somewhat arbitrary upper limit for a phone). MatchMedia is a good start for checking handheld but I'd always combine with a check for touch events (which is async so a good reason to save in localStorage).

@RRTW 2019-04-29 02:24:56

I'd prefer this way since a RWD designed page almost have some element need to be hide/show in mobile browser mode.

@Mladen B. 2019-05-15 07:08:03

This answer totally misses the point of the question. The OP asked how to detect a mobile device, not how to detect a small screen. Today's mobile devices have ridiculous screen resolutions and this approach is really wrong and misleading. In some cases, we need to detect a mobile device to disable "on hover" functionalities, which don't exist on mobile devices.

@WoodrowShigeru 2018-09-23 11:16:01

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.

@vin 2018-06-26 02:52:03

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
}

@QuasarDonkey 2014-07-06 21:46:31

According to Mozilla - Browser detection using the user agent:

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

@arminrosu 2015-04-03 09:24:47

Thanks for the answer! I prefer /Mobi/i.test(navigator.userAgent) though, as test() it returns a Boolean.

@Eirinn 2015-11-09 09:59:56

Paradoxically FireFox Mobile on an Samsung Galaxy Note 8 does not return Mobi and the test will return false.

@QuasarDonkey 2016-06-09 13:27:42

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

@RNobel 2017-02-07 11:26:53

This is much better than the other suggested solutions, it should be the accepted answer i.m.o.

@EricL 2017-04-12 23:38:02

I like this solution as well. Like it was mentioned earlier some Android tablets do not have "mobi" in there user agent string, but a quick fix to detect all phones and tablets might be to use the following: /Mobi/i.test(navigator.userAgent) || /Anroid/i.test(navigator.userAgent). This post suggests something like that: webmasters.googleblog.com/2011/03/…

@chilemagic 2017-04-17 14:53:35

@EricL you have a typo in Android in the code in your comment.

@EricL 2017-04-17 20:03:44

Derp. Thanks. I could not edit my previous post. Here it is again:/Mobi/i.test(navigator.userAgent) || /Android/i.test(navigator.userAgent)

@Erutan409 2017-08-14 15:14:52

As elegant as the other suggested solutions are, I must say this is more than likely the more practical one. It may be a moving target, but some light maintaining might still be the most suitable choice in this situation.

@Fabio 2017-11-08 11:49:00

is this solution still working? i get false positive on the current latest chrome

@Shnigi 2018-05-17 08:32:35

This looks like the correct answer for me, upvoted. Works well, tested just now with EricL version /Mobi/i.test(navigator.userAgent) || /Android/i.test(navigator.userAgent)

@Telarian 2019-02-06 21:36:52

To answer @Fabio this is still working correctly from what I can see.

@teknopaul 2012-07-14 07:58:54

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.

@Mickey 2015-12-10 23:48:01

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>

@Andrew Lazarus 2016-01-08 08:57:00

This doesn't relate to jQuery i'm afraid

@Mark 2013-01-24 15:10:33

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

@Mark 2018-03-31 22:10:08

Arbitrarily downvoting an answer without leaving a comment shouldn't be allowed. At best, it's rude.

@Gor 2018-02-23 07:38:13

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();

@mrReiha 2019-07-23 01:19:53

absolutely no need for arrow-syntax function.

@Vishnu Prasanth G 2018-03-01 15:09:39

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

@Mohamad Hamouday 2017-04-18 18:35:52

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

@NikitOn 2016-01-28 00:41:08

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);
    }

@arikan 2013-02-13 20:11:54

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');
}

@Akshay Khale 2015-11-05 05:12:20

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

@Kousha 2013-08-26 18:00:06

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

@Nur Rony 2013-03-16 16:25:29

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"));
};

@Luca Mori Polpettini 2015-04-21 16:08:38

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.

@Craicerjack 2018-04-10 15:41:41

Because the question asked for jQuery?

@Luca Passani 2014-03-11 17:20:54

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.

@Jacob 2014-04-03 12:53:06

Wurfl failed detecting nexus7 and iPad mini!

@Luca Passani 2014-04-03 13:48:32

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?

@Jacob 2014-04-03 13:50:02

No, the ipad mini was detected as a desktop device

@Jacob King 2015-12-08 17:54:00

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

@Jeff Mergler 2016-02-29 18:53:27

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.

@Developer 2017-02-23 12:20:32

That is I was looking for a while. Thank you!

@medBouzid 2017-10-01 23:47:48

@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 instead

@Maksim Luzik 2013-10-08 12:05:58

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.

@Maksim Luzik 2014-04-29 11:18:48

For me it was working, can you be more specific what code do you use and where seems to be an issue?

@Rubén Ruíz 2018-03-17 10:15:16

that page is response, of all other responses are copy paste of that page

@Ben H 2011-07-08 10:10:33

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");
}

@oriadam 2015-12-02 17:06:21

Many mobiles have width of >1000, especially on landscape mode

@Chris 2017-07-09 16:27:20

This would never work for any sort of tablet

@genkilabs 2011-06-09 18:26:17

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/

@Eric Allen 2011-09-15 15:04:46

This works great. I needed to disable a jQuery function that runs on scrolling when using an iPad or Android phone and since the various devices have differing screen widths, this was a simple solution. Thanks a ton.

@MayorMonty 2014-05-24 23:45:41

The only problem with using the test of Android is what about the nook which uses the android user agent

@Fernando 2015-01-09 07:37:54

Nice answer which shows we don't have to be feature detection fundamentalists.

@Ender 2010-08-18 18:02:13

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 :)

@Jayson Ragasa 2012-07-15 10:31:58

that does not support iPads. To support iPad, look for ip(hone|od) and "|ad" - e.g. ip(hone|od|ad)

@Milche Patern 2013-06-07 15:30:26

I just tried the javascript from detectmobilebrowser.com/, and IT IS NOT working for iPad.

@Coen Damen 2013-06-18 14:56:42

@MilchePatern that's because the script is faulty, use iPad instead of ipad, then it works, I had the problem on my Samsung Tab, had to use Android iso android :)

@cprcrack 2013-08-02 20:15:00

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)

@Felix Eve 2015-01-22 03:00:48

Well yeah, a tablet is not a mobile. The site is called dectect mobile browsers.

@Ricardo Nunes 2015-03-20 12:14:46

@FelixEve a tablet IS a mobile device, it just isn't a smartphone, so it should be detected. If you're doing CPU-intensive animations in JS, like I'm doing, you need to filter out all mobile devices, smartphones and tablets.

@Felix Eve 2015-03-22 21:44:58

@RicardoNunes in my case I needed to detect devices that were capable of making phone calls so I was not interested in tablets. Ideally I would use feature detection however that is not really possible across all devices at the moment.

@monteirobrena 2015-09-15 17:27:15

This does not work if you are using Chrome on your smartphone, will detect as desktop.

@Snickbrack 2016-03-29 11:36:59

this works very good and accurate if you're using the mobile "additions" from their ABOUT-page.

@sweets-BlingBling 2010-08-22 05:26:26

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

@Panthro 2011-09-12 16:07:24

ipad would be navigator.userAgent.match(/iPad/i) ?

@sweets-BlingBling 2011-09-16 10:38:32

Yes. The (String).match regular expression test checks for the presence of "iPad" in the user agent string.

@code ninja 2011-11-10 22:34:57

what about blackberry?

@sweets-BlingBling 2011-11-16 06:50:18

Try navigator.userAgent.match(/BlackBerry/),

@Rob 2012-01-09 10:42:51

User agent sniffing is a very noddy detection technique, user agent strings are a constant moving target, they should not be trusted alone. People up-voting this post should consider researching more.

@Brice Favre 2012-06-26 10:27:12

I think this is not a very good idea to tes user Agent

@ICodeForCoffee 2012-11-28 17:26:19

One of the problems with sniffing for just specific devices out of the user agent is that you have to remember to update your detection when new devices come out. This isn't an ideal solution.

@Brandon Buck 2013-01-10 21:12:36

User agent sniffing is not reliable and ever changing, this is not a good approach at all. webaim.org/blog/user-agent-string-history

@the_new_mr 2013-01-14 10:44:35

Hate to be an echo but the point can be emphasised enough. DON'T use user-agent detection.

@feeela 2013-01-24 14:31:07

The Dolphin browser on android does not send any of those strings!

@Michael Zaporozhets 2013-02-15 12:55:15

my answer over on this answer seems to offer the same deal but be a hell of a lot more comprehensive ( just a heads up ), with detection method credit going to detectmobilebrowsers.com

@mattdlockyer 2013-03-22 17:02:49

If your user is crafty enough or the developers dumb enough to change the user agent string, who cares about them...

@Throttlehead 2013-03-22 21:22:49

I agree Matt. If your application has very sensitive/important mission critical features, you're better off using a different approach, which will probably involve having an entirely separate mobile site/application. I'd argue that this is approach is probably acceptable for most cases. We're not in the mid 90's anymore guys...

@Abuzzy 2013-04-05 00:16:05

Agree with the "Don't do user agent sniffing" its not reliable, the better way to go is Feature detection like Modernizr modernizr.com

@user963714 2013-05-15 04:24:46

sniffing may be bad, but there is a number of scenarios where it is the only way to go. Like showing a pop-up window to Android and iOs users to install a mobile app while ignoring other less-popular mobile OSes.

@molokoloco 2013-05-30 12:35:18

var mobile = ('DeviceOrientationEvent' in window || 'orientation' in window); /* My Chrome desktop on window have DeviceOrientationEvent == fct() */ if (/Windows NT|Macintosh/i.test(navigator.userAgent)) mobile = false;

@Barlas Apaydin 2013-07-01 15:06:57

@sweets-BlingBling your native js detection is amazing but, is it possible to separate mobile and tablet devices on this equation?

@FrancescoMM 2013-07-04 09:58:43

So how mobile would you consider an android TV with mouse? How mobile is a windows PC that can run in dual mode (with keyboard, or as touch screen)? If you did this before the iPad was invented, then you had to add it later to all your sites. Next OSs coming out: Ubuntu Mobile, FirefoxOS, Tizen... .This.Is.A.Bad.Idea.

@Mike 2013-12-09 14:37:35

There are so many possible user agent strings missing from there. HP slate (HP Slate 7|HP ElitePad 900|hp-tablet|EliteBook.*Touch), Microsoft Surface (Windows NT [0-9.]+; ARM;), PSVita (Playstation.*(Portable|Vita)) ar ejust the ones off the top of my head. There are literally thousands of manufacturer-specific ones which don't include Android or similar in the string. Consider using a library that compiles these into an efficient test for you and just keep the library up to date.

@Neville Nazerane 2014-02-03 04:58:50

this does not work for Z10. what match do i use for Z10

@Dg Jacquard 2014-02-20 19:06:39

With the flag 'i' (ignore case) you do not need to use the toLowerCase() function.

@Dg Jacquard 2014-02-20 20:19:36

'applewebkit' is also a Chrome userAgent on the Desktop.

@giorgio79 2014-02-22 13:14:57

A lot of the mobiles would be missed from here useragentstring.com/pages/Mobile%20Browserlist

@Alex Vauch 2014-09-12 13:15:52

Modified @Andy Ray's version: (/iPhone|iPod|iPad|Android|BlackBerry|BB10|RIM Tablet|Windows Phone|SymbianOS|Kindle|Silk/).test(navigator.userAgent). Some Black Berry, WP, Symbian, Amazon, Playstation devices have been added to regex.

@SpYk3HH 2015-03-27 17:40:37

add Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPW‌​A|KFAPWI to that

@Bobby Russell 2015-11-11 22:41:03

This works for jQuery (as constrained by the question itself,) but I think it should be said that it's probably not a good idea to test against user against. @BriceFavre has also mentioned this. Something like modernizr is probably a better solution.

@Mateus Viccari 2016-06-07 12:06:23

@Bobby Russell But what does modernizer do under the table?

@kodmanyagha 2017-01-28 18:28:16

I created a Jquery plugin for only this purpose: github.com/nixarsoft/mobilebrowser/blob/master/… You can use this like this: if( $.isMobile() ) { alert("mobile"); } else { alert("not mobile"); }

@RNobel 2017-02-07 11:28:42

A better approach is to follow Mozilla´s recommendation on detecting a mobile device: developer.mozilla.org/en-US/docs/Web/HTTP/…. See the following answer below: stackoverflow.com/a/24600597/1829959

@BugWhisperer 2017-05-16 22:10:58

@Rob are you aware of any better alternatives??

@phk 2017-05-18 13:01:53

@Anthony CSS media queries, feature detection, …

@BugWhisperer 2017-05-18 18:48:04

@phk CSS3 since the resolution of some cellphones nowadays is better than some old laptops and desktop monitors, just how reliable are css3 media queries? or am i missing something?

@phk 2017-05-18 18:53:05

@Anthony device-pixel-ratio, orientation, matching DPI (hacks.mozilla.org/2013/09/css-length-explained)

@Rob 2017-05-25 09:10:57

@Anthony yes, feature detection as many others including phk have suggested. You can enhance a users experience by checking the feature you want is available in their browser.

@Telarian 2019-02-06 21:36:06

Good lord man, at least offer a warning along with your answer. It can way wrong in a hurry.

@Rohan Varma 2019-02-26 13:07:44

Perfect. Its working for me

@Daniel Kucal 2018-02-15 15:26:46

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.

@Rasmus Søborg 2013-04-18 10:19:21

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

@Gruber 2013-06-01 17:08:53

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 workaround

@Ankit Sain 2017-06-06 06:41:40

Use this

if( screen.width <= 480 ) { 
    // is mobile 
}

@Liam 2017-08-02 12:33:30

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

@sequielo 2013-11-29 21:14:18

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

@Chris Cinelli 2013-12-26 23:23:23

What about Windows laptops with touch screen?

@Luke 2015-08-22 11:26:02

The second isMobile function you provided returns true on my destop device!! (Google Chrome v44.0)

@Martin Barker 2016-05-01 16:04:05

This is more of a isTouchSupported method not really mobile detection.

@Andrew 2017-05-03 23:18:07

Not all mobile phones have touch screens.

@Christian4423 2018-01-10 18:17:19

@LukeP Are you refreshing when going from mobile emulation to desktop?

@Telarian 2019-02-06 21:37:43

@Andrew but honestly, no one cares about those phones lol

@Andrew 2019-02-06 22:39:13

@Orion, according to GSM Arena, 26 mobile phones have been released since 2017 without a touch screen, 7 of those are by Nokia. So beware! :P

@Telarian 2019-02-07 15:00:31

@Andrew but from a developer perspective, those devices must be such a tiny percentage of mobile users that they're not worth catering to. Especially in the U.S.

@Andrew 2019-02-07 17:23:11

@Orion, yes, I thought the irony was obvious. :)

@Alex Jolig 2017-06-06 06:05:42

Knowing that TouchEvent is only for mobile devices, Maybe the simplest way could be check if user device can support it:

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

@Ismail Farooq 2017-06-06 06:12:48

TouchEvent is not only for mobile its available for touch laptop also

@Alex Jolig 2017-06-06 06:14:27

@IsmailFarooq By mobile devices I meant those too.

@Ismail Farooq 2017-06-06 06:15:32

the OP ask for detecting mobile devices only

@Alex Jolig 2017-06-06 06:24:21

@IsmailFarooq So you think the highest voted answers just return true on mobiles? doesn't tablets use android?

Related Questions

Sponsored Content

69 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

34 Answered Questions

16 Answered Questions

23 Answered Questions

77 Answered Questions

[SOLVED] How do I detect a click outside an element?

  • 2008-09-30 13:17:12
  • Sergio del Amo
  • 1132133 View
  • 2320 Score
  • 77 Answer
  • Tags:   javascript jquery

41 Answered Questions

[SOLVED] Detecting an "invalid date" Date instance in JavaScript

  • 2009-08-30 11:34:40
  • orip
  • 713185 View
  • 1326 Score
  • 41 Answer
  • Tags:   javascript date

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

32 Answered Questions

[SOLVED] Detecting a mobile browser

36 Answered Questions

[SOLVED] What's the best way to detect a 'touch screen' device using JavaScript?

20 Answered Questions

[SOLVED] jQuery get specific option tag text

Sponsored Content