I try to use javascript to get mobile device viewport size, here I found some nice answer on the stackoverflow:
- Find the exact height and width of the viewport in a cross-browser way (no Prototype/jQuery)
- Get the browser viewport dimensions with JavaScript
They both recommend using window.innerHeight
and window.innerWidth
to get viewport size like this:
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
But I found this way sometime can not be accurate, when the device's browser have tool bar or address bar. So I figure out a way using devicePixelRatio
to get mobile device viewport size:
if (window.devicePixelRatio) {
var physicsWidth = window.screen.width;
var physicsHeight = window.screen.height;
var viewportWidth = physicsWidth / window.devicePixelRatio;
var viewportHeight = physicsHeight / window.devicePixelRatio;
}
Is this way OK to get viewport size?