1

I need to find the screen width of a device with JavaScript, I am unable to change the html and do not want to inject the meta viewport tag before doing so. Essentially I need to detect whether the device width is below 600px (in CSS pixels).

I have seen various recommendations but unfortunately I am getting different behaviour between iOS Safari and the default Android browser:

Command                                           iPhone4     GalaxyS3
------------------------------------------------------------------------
window.devicePixelRatio                           2           2      
window.innerWidth                                 982         626  
window.outerWidth                                 326         720
screen.width                                      320         720 
screen.availWidth                                 320         720  
matchMedia('(max-width: 599px)').matches          false       false
matchMedia('(max-device-width: 599px)').matches   true        false

Unfortunately the inconsistencies of the above values means I don't seem to be able to do it with JavaScript (e.g. I could divide screen.width by window.devicePixelRatio on Android, but this would then be incorrect on iOS).

Is there a reliable, cross browser way of doing this?

Community
  • 1
  • 1
Alasdair McLeay
  • 2,572
  • 4
  • 27
  • 50

1 Answers1

3

You could try using Verge viewport utility. It's an open source library. Then you could simply use:

$.viewportW() // Get the viewport width in pixels.

Hope this helps!

2kreate
  • 148
  • 1
  • 10
  • this seems to work, ideally I don't want to include an entire library for just one function but it's definitely an option.. thanks! I'll try read through the Verge source to see what they're doing – Alasdair McLeay Dec 03 '13 at 18:04
  • @penx You could try... document.documentElement.clientWidth – 2kreate Dec 03 '13 at 20:39