1965

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.

17
  • 9
    Provide a mobile URL specifically for mobile devices. This is how most major sites handle mobile devices. See m.google.com. Commented Aug 18, 2010 at 17:27
  • 7
    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. Commented Aug 22, 2010 at 5:38
  • 88
    User agents are constantly moving targets, everyone reading this post should be very wary of user agent sniffing Commented Jan 9, 2012 at 10:38
  • 58
    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. Commented Jul 9, 2013 at 4:42
  • 7
    @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. Commented Aug 20, 2013 at 2:38

65 Answers 65

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

Sign up to request clarification or add additional context in comments.

2 Comments

so then what do u suggest using for "real" validation??
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.
4

You could do simple thing very simple like this

(window.screen.width < 700) { //The device is a Mobile } else { //The device is a Desktop } 

3 Comments

Just because the viewport is < 700 does not make the device mobile
@sea26.2 This is true. However, for our purposes, it actually works better, because we want our javascript to interact correctly with our CSS media queries.
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) ?
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'){...} 

1 Comment

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

1 Comment

Please use feature detection, not User-Agent sniffing.
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.

1 Comment

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

1 Comment

Why would you need to call this code in an animation/scroll event/etc.?
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.]

2 Comments

+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.
Please use feature detection, rather than targetting specific devices.
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); } 

1 Comment

That should not matter, because you should be using feature detection rather than User-Agent sniffing.
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') } 

1 Comment

If I resize my desktop window to less than 760px wide, this fails.
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.

Comments

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

1 Comment

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

1 Comment

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

1 Comment

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

^^

Comments

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) 

2 Comments

is window.opera necessary? what does it do exactly?
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?
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.

Comments

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

1 Comment

Please user feature detection.
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'); } 

1 Comment

Please stop recommending this.
1

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

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

2 Comments

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.
window.orientation is unfortunately deprecated now, and its replacement works on desktop too - so no longer useful I'm afraid. :(
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

1 Comment

Please don't. Please use feature detection, rather than detecting specific device types.
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(); 

2 Comments

absolutely no need for arrow-syntax function.
@mrReiha No need for this at all, arrow-syntax or otherwise. User-Agent sniffing is the wrong approach.
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; } 

2 Comments

is there any reason to try creating a touch event instead of checking if touchstart exists?
Many desktops have a touch screen too. And the window can be resized.
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?

Comments

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

Comments

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

1 Comment

This answer is out of context. The OP does not have an element with ID mobileNav.
-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.)

Comments

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

4 Comments

This is the wrong approach, so we will not be updating your array.
@Jake I don't know who we are and what array updating you are talking about. This works regardless of the OS version.
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.
You put "help updating the array" in your 'answer'. Then said you didn't know "what array updating [I am] talking about". Really?
-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> 

2 Comments

This doesn't relate to jQuery i'm afraid
Nor does it relate to the OP.
-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) ); 

1 Comment

Please use feature detection not User-Agent sniffing.
-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> 

1 Comment

This is incomplete. You are relying on a function that is not included in the answer to do all the work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.