views:

4330

answers:

2

How do I detect the width of a user's window with Javascript and account for their scrollbar? (I need the width of the screen INSIDE of the scrollbar). Here's what I have...it seems to work in multiple browsers...except that it doesn't account for the scrollbars..

    function browserWidth() {
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && document.documentElement.clientWidth ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && document.body.clientWidth ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return myWidth;
}

any ideas? i need it to work in all browsers;)

+2  A: 

You will find the big summary of what properties are supported on what browsers on this page on quirksmode.org.

Your best bet is probably to grab an element in the page (using document.body where supported, or document.getElementById or whatever), walk its offsetParent chain to find the topmost element, then examine that element's clientWidth and clientHeight.

moonshadow
A: 

I would compare the "innerWidth" to the width of the body. If the body width > innerwidth, then scrollbars are present.

if (browserWidth() < document.body.offsetWidth) {
  doSomething();
}
tj111
hmmm cool...i guess im at a loss of WHAT to do when i figure out if scrollbars are present...since browsers have different sized scrollbars...ideas?
johnnietheblack
@johnintheblack: Please take note that in windows, changing the windows theme causes the scrollbars to chagne width, so this needs to be taken into account when testing. The vista default theme's width is 8 pixels larger than the default theme for xp, for example.
diadem