Getting the scrollbar width in pixels

Description Javascript

Working on the new fluid layout code for Scooby, I had a seemingly intractable problem -- I needed to do percent-based side-to-side alignment of elements inside two div elements, one positioned directly above the other. The catch was that the lower div scrolled, and the upper one did not.

I tried two or three different things, but couldn't get around it -- ultimately I needed to set a horizontal offset on the top div that would be the same precise width as the scrollbar in the div below.

Interestingly, the irritatating IE bug of calculating the 100% width before adding scrollbars to a scrolling div makes this unnecessary -- all you have to do is set the same arbitrary offset for both div elements (as long as it's wider than any Windows scrollbar might be so you don't end up with content under the scroller).

For the well-behaved browsers, though, I just decided to do some hacking, and came up with something that reliably gives you the actual pixel width of the scroller. There is likely a better way to do it, but here's what I ended up with:

Author: Fleegix (Website)

The Code Download

  1. function getScrollerWidth() {
  2.     var scr = null;
  3.     var inn = null;
  4.     var wNoScroll = 0;
  5.     var wScroll = 0;
  7.     // Outer scrolling div
  8.     scr = document.createElement('div');
  9. = 'absolute';
  10. = '-1000px';
  11. = '-1000px';
  12. = '100px';
  13. = '50px';
  14.     // Start with no scrollbar
  15. = 'hidden';
  17.     // Inner content div
  18.     inn = document.createElement('div');
  19. = '100%';
  20. = '200px';
  22.     // Put the inner div in the scrolling div
  23.     scr.appendChild(inn);
  24.     // Append the scrolling div to the doc
  26.     document.body.appendChild(scr);
  28.     // Width of the inner div sans scrollbar
  29.     wNoScroll = inn.offsetWidth;
  30.     // Add the scrollbar
  31. = 'auto';
  32.     // Width of the inner div width scrollbar
  33.     wScroll = inn.offsetWidth;
  35.     // Remove the scrolling div from the doc
  36.     document.body.removeChild(
  37.     document.body.lastChild);
  39.     // Pixel width of the scroller
  40.     return (wNoScroll - wScroll);
  41. }


Added by JC on 14th November 2007


There are no comments about this snippet.

Post Comment Github Markdown Supported

You must be logged in to post a comment.

Login here to post a comment