Robbin Ploeger
Robbin Ploeger

Reputation: 43

Getting the exact physical mobile resolution in javascript

I'm building a page that shows the user as much information about their device as possible. For mobile devices the physical resolution is not the same as the resolution interpreted by the browser, because otherwise high resolution devices would not display pages very well.

For example, my Moto X Style has a resolution of 1440 x 2560 pixels, which is even higher than most PC monitors. It is scaled down by the device pixel ratio, which is set to 3.5 on my device. this makes the 'interpreted resolution' 412 x 732 pixels

For many devices it would be sufficient to multiply the interpreted resolution of screen.[width/height] and multiply it by window.devicePixelRatio. However in my case this is only an estimate, and comes out at 1442 x 2562, presumably because of rounding.

Is there a surefire way to get this exact value? Or maybe suppress the rounding in these values? Any thoughts are appreciated.

Upvotes: 1

Views: 728

Answers (3)

PHPDev
PHPDev

Reputation: 81

I use these to get the width/height of the window of the browser.

getWindowWidth: function() {
    if (true) {
        try {
            return document.documentElement.clientWidth;
        } 
        catch (error) {}
    } 
    else {
        try {
            return window.innerWidth;
        } 
        catch (error) {}
    }
    return 0;
},

getWindowHeight: function() {
    if (true) {
        try {
            return document.documentElement.clientHeight;
        } 
        catch (error) {}
    } 
    else {
        try {
            return window.innerHeight;
        } 
        catch (error) {}
    }
    return 0;
},

Upvotes: 0

blrzzzt
blrzzzt

Reputation: 194

Check out this page :

http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html

Apparently it changes per device, but you're on the right track with:

Math.round(screen.width||height*window.devicePixelRatio)

Best of luck.

Upvotes: 1

Kirankumar Dafda
Kirankumar Dafda

Reputation: 2384

You can try this to get exact height width of current device

var w = window.innerWidth;
var h = window.innerHeight;

Upvotes: 0

Related Questions