views:

5685

answers:

2

document.body.offsetWidth returns the innerwidth value from left hand side to the left side of the vertical scrollbar in firefox. In IE it doesn't, instead it returns from left hand side to the right side of the vertical scrollbar. Does anyone know a sensible way I could make a veriable such as "var = offsetw;" for offsetw to be the scrollbar width I need to subtract to get a firefox like document.body.innerWidth value? Heres what I have.

if (parseInt(navigator.appVersion)>3) {
 if (navigator.appName=="Netscape") {
  winW = 16;
  winH = 16;
 }
 if (navigator.appName.indexOf("Microsoft")!=-1) {
  winW = 20;
  winH = 20;
 }
 if (navigator.appName.indexOf("Mozilla")!=-1){
  winW = 0;
  winH = 0;
 }
}

Firefox currently uses the 16 value and not the zero declared by the Mozilla line, which indicates it is wrong.

I'm after an addition or fix to get winW and winH to the correct size of the scrollbar for each browser only if those browsers don't subtract the scrollbar from document.body.offsetWidth automatically

Thanks :)

+1  A: 

Have you tried a javascript library? it is the easiest way to get rid of these problems. I recommend: jquery or YUI (Yahoo user interface), where everything is wrapped in classes that make code compatible for almost every browser.

Apart of this consideration, in the following pages you can find a function to know the width of the scrollbar (i haven't tested):

http://www.alexandre-gomes.com/?p=115

http://javascript.jstruebig.de/javascript/70/

The code is this (i don't know if it is compatible to all browsers):

function scrollbarWidth() {

    // Scrollbalken im Body ausschalten

    document.body.style.overflow = 'hidden';

    var width = document.body.clientWidth;



    // Scrollbalken

    document.body.style.overflow = 'scroll';



    width -= document.body.clientWidth;



    // Der IE im Standardmode

    if(!width) width = document.body.offsetWidth-document.body.clientWidth;



    // urspr?ngliche Einstellungen

    document.body.style.overflow = '';



    return width;

}
netadictos
I also reccomend jQuery. There you can use $(document).width() or .height() and also with the dimensions-plugin offset().left and offset().top.
powtac
+2  A: 

document.body.offsetWidth returns the innerwidth value from left hand side to the left side of the vertical scrollbar in firefox.

Not for me it doesn't, it returns the same value as IE, Opera, Konqueror and Safari. Example code?

Sniffing browser by appName is very unreliable at the best of times and doesn't cover it in this case anyway because the size of a scrollbar is influenced more by operating system and user preferences than the browser.

Instead, if you want to read the ‘inside size’, use clientWidth/clientHeight instead of offsetWidth/offsetHeight, or measure the offsetWidth of a block inside the one with the scrollbar.

bobince