1

I'm using this javascript to detect the browser width:

$(document).ready(function(){ var width = window.innerWidth; });

It appears to be giving inconsistent results. I've made a working codepen here. by repeatedly refreshing the full-page view in mobile Safari I've received both of the following results:

ios9 Mobile Safari window.innerWidth ios9 Mobile Safari window.innerWidth

It jumps back and forth inconsistently, and appears to be exacerbated by a larger page size (hence all the images). Sometimes it will only return one result until I kill the app and re-open it.

Is there a better way to get the width of the browser?

Notes:

  • I've added this to the head: <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
  • Using $(window).width() isn't really an option for me because it doesn't account for scrollbars
  • I know I could put the js in a timeout function, but this solution is problematic for me since I'm storing the result in a variable that I'm using in various places throughout the website.
  • I'm using an iPhone 5 running iOS 9.2

Thanks!

launchoverit
  • 4,807
  • 4
  • 20
  • 23
  • One quick note - I recognize some variation of this question has been asked several times before, but so far I haven't found a solution that actually adresses my criteria. Appoligies if I'm wrong about that though! – launchoverit Jan 06 '16 at 23:26
  • Update: Not a direct answer to this question, but thought I would mention that I did find some great workarounds here - http://stackoverflow.com/questions/19291873 – launchoverit Jan 08 '16 at 00:33

1 Answers1

1

Safari gets inconsistent widths in vanilla javascript because of the resolution. JQuery usually standardised this. Try using:

$(window).width()

This should give you the right width.

DoubleA
  • 1,636
  • 14
  • 28
  • Thanks for the suggestion! However it looks like jQuery.com says re:innerWidth - "This method is not applicable to window and document objects; for these, use .width() instead." – launchoverit Jan 08 '16 at 00:08
  • Sorry, meant to put `width()`, I copied it from your question :) – DoubleA Jan 08 '16 at 13:45
  • 1
    I just re-read your question, and saw you mention not wanting to use `width()`. However, in my experience this is the only way I have been able to get a definitive width on all browsers. If your issue is deducting the scrollbars from the page width, you might find this solution useful: http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes – DoubleA Jan 08 '16 at 14:06
  • If I end up needing to go that route that will be helpful, thanks! – launchoverit Jan 08 '16 at 16:30