Pages

Friday, April 27, 2012

JavaScript to get the browser window's height and width

While working on a web application I came across a scenario where in I wanted to adjust height and width of my component as per browser's resolution. And here is the code snippet to do that in JavaScript.

function getScreenHeightWidth() {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        // Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement
            && (document.documentElement.clientWidth 
                        || document.documentElement.clientHeight)) {
        // IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body
            && (document.body.clientWidth 
                        || document.body.clientHeight)) {
        // IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    window.alert('Width = ' + myWidth);
    window.alert('Height = ' + myHeight);
}

I have tested this in latest versions of all modern browsers including Chrome, Firefox, Safari and Internet Explorer. Also I have tested it in Windows 7, Ubuntu 11.10 and Mac Snow Leopard.

No comments:

Post a Comment