views:

1311

answers:

3

How to determine the height of an horizontal scroolbar, or the width of a vertical one in javascript ?

+3  A: 

From Alexandre Gomes Blog I have not tried it. Let me know if it works for you.

function getScrollBarWidth () {
  var inner = document.createElement('p');
  inner.style.width = "100%";
  inner.style.height = "200px";

  var outer = document.createElement('div');
  outer.style.position = "absolute";
  outer.style.top = "0px";
  outer.style.left = "0px";
  outer.style.visibility = "hidden";
  outer.style.width = "200px";
  outer.style.height = "150px";
  outer.style.overflow = "hidden";
  outer.appendChild (inner);

  document.body.appendChild (outer);
  var w1 = inner.offsetWidth;
  outer.style.overflow = 'scroll';
  var w2 = inner.offsetWidth;
  if (w1 == w2) w2 = outer.clientWidth;

  document.body.removeChild (outer);

  return (w1 - w2);
};
Matthew Vines
The idea is genius, I'm definitely making a MooTools class based on this.
rpflo
Yeah I got the same google result. :) I'm trying and keep you informed.
subtenante
Gives me 16 pixels, but counting on my screen I get 17.
subtenante
if you change your theme to one with different sized scroll bars what is the deviance in calculated to actual?
Matthew Vines
Changed the theme to Extra Large in windows, double checked in Normal size, the computation seems correct. I apparently counted wrongly.
subtenante
see here for cross reference : http://stackoverflow.com/questions/3417139/how-do-i-calculate-the-height-of-toolbars-address-bars-and-other-navigation-tool/3417992#3417992
Yanick Rochon
+1  A: 
window.scrollBarWidth = function() {
  document.body.style.overflow = 'hidden'; 
  var width = document.body.clientWidth;
  document.body.style.overflow = 'scroll'; 
  width -= document.body.clientWidth; 
  if(!width) width = document.body.offsetWidth - document.body.clientWidth;
  document.body.style.overflow = ''; 
  return width; 
}
Josh Stodola
Works as well but shorter code. Thanks.
subtenante
Doesn't work if the body has a fixed width.
Pumbaa80
+1  A: 

Here is a snippet from the author of the JQuery Dimension plugin.

http://github.com/brandonaaron/jquery-getscrollbarwidth/blob/master/jquery.getscrollbarwidth.js

maybe late to give this solution, but it seems a better one to me, IMO.

Yanick Rochon