dsol828
dsol828

Reputation: 413

Using jquery to determine screen width

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!

Upvotes: 16

Views: 62349

Answers (8)

Fritz
Fritz

Reputation: 411

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

Upvotes: 0

Tom John
Tom John

Reputation: 784

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

Upvotes: 2

MaxRocket
MaxRocket

Reputation: 992

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

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

Upvotes: 0

ekuusela
ekuusela

Reputation: 5312

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

Upvotes: 19

Sami
Sami

Reputation: 2110

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

Upvotes: 3

Bill Criswell
Bill Criswell

Reputation: 32941

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

Upvotes: 0

anon
anon

Reputation:

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.

Upvotes: 19

ScottMichaud
ScottMichaud

Reputation: 343

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

Upvotes: 2

Related Questions