4

I've been using the following code to detect browser client area width for ages and it wokred 100% with all browsers, including FF, Safari and various versions of IE. However, now when I switched to a new monitor with widescreen resolution (1280x800) this code fails on IE8. It reports clientwidth of 1024 !!!???

Any ideas how to get the correct client area width ?

function getClientWidth() {
  var v=0,d=document,w=window;
  if((!d.compatMode || d.compatMode == 'CSS1Compat') && !w.opera && d.documentElement && d.documentElement.clientWidth)
    {v=d.documentElement.clientWidth;}
  else if(d.body && d.body.clientWidth)
    {v=d.body.clientWidth;}
  else if(xDef(w.innerWidth,w.innerHeight,d.height)) {
    v=w.innerWidth;
    if(d.height>w.innerHeight) v-=16;
  }
  return v;
}
Demiurg
  • 1,597
  • 8
  • 26
  • 40

2 Answers2

5

Non-jquery code I used some time ago:

function detectBrowserSize() {
    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;
    }
    alert(myWidth + ' - ' + myHeight)
}
Marc Uberstein
  • 12,501
  • 3
  • 44
  • 72
  • Good bit of code. I will thinking about this all wrong. I was trying to use this to display a dialog dead center. So i added the following: topMargin = (viewportheight + (detectBrowserHeight()/2))-(divInner.offsetHeight / 2); divInner is the div i am displaying as a dialog – user3759531 Jan 20 '16 at 16:00
0

The bits in your code where you check for window.opera and subtract 16 pixels are worrying. comp.lang.javascript's FAQ has a decent implementation of this.

Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • I agree that it does not look good, but it works OK. This is supposed to account for scrollbars. I will check you link, 10x. – Demiurg Oct 19 '09 at 08:53