18

I need to find the device-width of the mobile device. Although we can specify the content

<meta name="viewport" content="width=device-width; user-scalable=no" />

But i need to programmatically obtain the device width to compute some logic in my application. How can I get the device width?

2 Answers 2

41

The viewport dimensions can be gathered via the window object:

var viewport = {
    width  : $(window).width(),
    height : $(window).height()
};

//can access dimensions like this:
//viewport.height

Though you won't always get perfect results, different devices behave differently and this gives the viewport dimensions, not the screen dimensions.

Alternatively you could check the width of a data-role="page" element to find the device-width (since it's set to 100% of the device-width):

var deviceWidth = 0;
$(window).bind('resize', function () {
    deviceWidth = $('[data-role="page"]').first().width();
}).trigger('resize');​​​
Sign up to request clarification or add additional context in comments.

3 Comments

Hey jasper i need to get this device width in <body> so that i can place myWidth as like here <div id="placeholder" style="width:myWidth;height:150px"></div>
@Coder_sLaY Then go with my first example: $('#placeholder').width($(window).width());.
The jquery fiddle is dead now. Can you update your answer so that it will be helpful for future users
18

Not sure that the solution proposed works as expected. Are you sure you get the real device-width?

I'm using the following code in my app and it works fine:

function effectiveDeviceWidth() {
    var deviceWidth = window.orientation == 0 ? window.screen.width : window.screen.height;
    // iOS returns available pixels, Android returns pixels / pixel ratio
    // http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html
    if (navigator.userAgent.indexOf('Android') >= 0 && window.devicePixelRatio) {
        deviceWidth = deviceWidth / window.devicePixelRatio;
    }
    return deviceWidth;
}

Hope it can help someone!

2 Comments

this a great function. this helped me. but to get the good width for me I reverse : var deviceWidth = window.orientation == 0 ? window.screen.height : window.screen.width;
Works great! I also needed to reverse the conditional statement like llyas mentioned and then it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.