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.


@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); = id;
        js.src = "//";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

You can see it in action at

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:

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.

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

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

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

@Ryan Boken 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.

@que1326 2019-11-06 13:06:03

I love this approach so much, thank you for the reply man, wish you the best !!

@Jason Lydon 2020-02-13 16:44:37

I like this approach, I lifted window.matchMedia("(pointer:coarse)").matches; from a different answer.

@Ivan 2020-03-29 11:25:28

@JasonLydon, thanks a million for that comment! It's the best solution by far!

@Sir Papilonius 2020-06-03 20:48:15

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.

@Bienfait Rukundo 2020-05-17 09:09:34

You could do simple thing very simple like this

/* the device is a Mobile*/
 /*the device is a Desktop*/

@AmerllicA 2020-04-26 17:28:19

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

@Lauro Moraes 2020-04-10 08:10:05

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

        // 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 || !== "(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 which is no longer in operation.

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



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

@Pinonirvana 2020-03-03 09:44:05

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

if (typeof window.orientation !== "undefined" || navigator.userAgent.indexOf('IEMobile') !== -1) {

@Gaby_64 2020-05-15 19:00:23

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.

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

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;

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

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

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

@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

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

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

@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

@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


@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:… 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:…. See the following answer below:

@oldboy 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, …

@oldboy 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 (

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

@Bill Keese 2019-11-11 21:10:04

Hmm, this breaks on iOS 13.2, where mobile safari's userAgent is "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Safari/605.1.15".

@nelek 2019-10-12 12:20:29

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 less than 10px 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>

@James 2020-01-27 11:47:09

I like this solution, are there any reason why we shouldn't use this?

@Ivan 2020-05-03 07:51:50

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)

@Twil 2019-09-27 16:08:31

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

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";
            screenType = "Tablet";
        screenType = "Desktop";
  return screenType;

@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) ||
) {
  // 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"}

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

@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

@Jason Lydon 2020-02-13 16:45:06

I like this approach, I lifted window.matchMedia("(pointer:coarse)").matches; from a different answer.

@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:…

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

@Halil 2019-10-17 06:55:03

It doesn't support Opera. See navigator.userAgent output in the image. It contains "Mobile Safari":

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

var isMobile = $('html').hasClass('ismobiledevice');

@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';


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

absolutely no need for arrow-syntax function.

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

  function checkIsMobile(){
      if(navigator.userAgent.indexOf("Mobile") > 0){
        return true;
        return false;

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||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';
            Return_Device = 'Mobile';
    else if(/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i.test(navigator.userAgent)) 
        Return_Device = 'Tablet';
        Return_Device = 'Desktop';

    return Return_Device;

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


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

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

You can use simply say:

if (bowser.msie && bowser.version <= 6) {
  alert('Hello China');
} else if (bowser.firefox){
  alert('Hello Foxy');
} else if ({
  alert('Hello Silicon Valley');
} else if (bowser.safari){
  alert('Hello Apple Fan');
} else if(bowser.iphone ||{
  alert('Hello mobile');

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

Checkout 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

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

In a nutshell, if you import a tiny JavaScript file:

<script type='text/javascript' src="//"></script>

You will be left with a JSON object that looks like:

 "complete_device_name":"Google Nexus 7",

(That's assuming you are using a Nexus 7, of course) and you will be able to do things like:

if(WURFL.is_mobile) {

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:

@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: It has ready made code in different languages for mobile detection (including but not limited to):

  • Apache
  • ASP
  • C#
  • IIS
  • JavaScript
  • 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, 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

Related Questions

Sponsored Content

28 Answered Questions

36 Answered Questions

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

80 Answered Questions

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

36 Answered Questions

[SOLVED] Detecting a mobile browser

44 Answered Questions

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

  • 2009-08-30 11:34:40
  • orip
  • 843435 View
  • 1527 Score
  • 44 Answer
  • Tags:   javascript date

35 Answered Questions

17 Answered Questions

20 Answered Questions

[SOLVED] jQuery get specific option tag text

67 Answered Questions

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

Sponsored Content