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;
  6.  
  7.     // Outer scrolling div
  8.     scr = document.createElement('div');
  9.     scr.style.position = 'absolute';
  10.     scr.style.top = '-1000px';
  11.     scr.style.left = '-1000px';
  12.     scr.style.width = '100px';
  13.     scr.style.height = '50px';
  14.     // Start with no scrollbar
  15.     scr.style.overflow = 'hidden';
  16.  
  17.     // Inner content div
  18.     inn = document.createElement('div');
  19.     inn.style.width = '100%';
  20.     inn.style.height = '200px';
  21.  
  22.     // Put the inner div in the scrolling div
  23.     scr.appendChild(inn);
  24.     // Append the scrolling div to the doc
  25.  
  26.     document.body.appendChild(scr);
  27.  
  28.     // Width of the inner div sans scrollbar
  29.     wNoScroll = inn.offsetWidth;
  30.     // Add the scrollbar
  31.     scr.style.overflow = 'auto';
  32.     // Width of the inner div width scrollbar
  33.     wScroll = inn.offsetWidth;
  34.  
  35.     // Remove the scrolling div from the doc
  36.     document.body.removeChild(
  37.     document.body.lastChild);
  38.  
  39.     // Pixel width of the scroller
  40.     return (wNoScroll - wScroll);
  41. }

Credits

Added by JC on 15th November 2007

Comments

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