Alasdair McLeay
Alasdair McLeay

Reputation: 2652

Finding screen width of HD device with JavaScript

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?

Upvotes: 1

Views: 144

Answers (1)

2kreate
2kreate

Reputation: 148

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!

Upvotes: 3

Related Questions