15

Having trouble getting this script to run properly on an iphone 6. Keeps coming up as "not mobile". What am I missing?

$(document).ready(function(){
    if ($(window).width < 700){
        alert("mobile");
    }
    else {
        alert("not mobile");
    }
});

EDIT: apologies, the code I typed here had a typo, but was not the cause for my issue. I had inaccurate info on iphone resolution. Thanks everyone!

dsol828
  • 403
  • 1
  • 6
  • 16

8 Answers8

19

The iPhone 6 display has a resolution of 1334x750. When emulating iPhone6 in chrome dev tools the width is reported as 980 (I don't know if this is accurate).

You might be interested in this: http://detectmobilebrowsers.com/

Also, as others have noted, replace $(window).width with $(window).width()

ekuusela
  • 5,034
  • 1
  • 25
  • 43
  • Whats the difference between viewport size and resolution? http://viewportsizes.com/?filter=iphone%206 – dsol828 Apr 26 '15 at 20:53
  • The site does not show any infos about device width/height. Go to whatismyscreenresolution.net instead. – Black Jan 24 '20 at 10:23
  • As this is old, I'm not sure you have figured it out the problem with mobile screens. But this solved the issue for me. Just add this in your tag. `` – Omar Omeiri Jul 16 '20 at 19:19
18

Well, ignoring what ekuusela said about screen resolution, you seem to have forgotten your parentheses after width, which is a method, not a field. To fix this, just add () after it:

if ($(window).width() < 700)

See the documentation for width() for more info.

Community
  • 1
  • 1
Nic
  • 6,211
  • 10
  • 46
  • 69
3

iPhone6 screen is 1334x750 pixels. If you only use the width to detect mobile user, see this instead.

Community
  • 1
  • 1
Sami
  • 2,050
  • 1
  • 13
  • 25
2

JQuery uses $(window).width(). It's a function, not a property.

ScottMichaud
  • 343
  • 3
  • 7
2

If you are using bootstrap add an element to the screen that only displays at a certain break point (bootstrap 4):

<div id="IsMobile" class="d-block d-lg-none"></div>

Then if it's visible:

if ($("#IsMobile").is(":visible")) {
     //Do Something...
}
Tom John
  • 783
  • 5
  • 14
0

You would want .width(), not just .width. Also, log it and make sure it's what you're expecting.

Bill Criswell
  • 32,161
  • 7
  • 75
  • 66
0

This thread gets deep into the options both in Javascript and JQuery

Get the size of the screen, current web page and browser window

MaxRocket
  • 920
  • 1
  • 12
  • 26
0
function isMobileDevice() {
    return (typeof window.orientation !== "undefined") || 
        (navigator.userAgent.indexOf('IEMobile') !== -1);
}

This is a legacy way of checking. You should probably use something like this:

const isMobile = ('ontouchstart' in document.documentElement && /mobi/i.test(navigator.userAgent));
Fritz
  • 343
  • 1
  • 10