jQuery Minute™

jQuery Minute is a term I coined in how fast and easy jQuery makes coding. "It only takes a jQuery Minute!"

Calculating The Browser Scrollbar Width

Recently I needed to calculate the browser's scrollbar width for FF 1.5+, IE6 and IE7 (supported browsers for the app). Google returned a handful of solutions with Fleegix.org: Getting the scrollbar width in pixels as the most relivant. One problem though, it doesn't work in the wonderful cursed IE7 browser. Also it doesn't leverage jQuery (...have I mentioned jQuery before? be SURE to check it out and see if it fits your needs).

This solution differ's from Feegix's solution only in leveraging jQuery and not setting a width to the innerMost div. When the div is set to 100%, IE7 will ignore the space that the scrollbar takes up. Since the div is a block element, it will expand by default and respect the scrollbar width.

So here are the steps and then to the code:

  1. Append two dives to the body and position them off screen
  2. Measure the width of the inner div
  3. Set the outer div to overflow
  4. Measure the width of the inner div (again)
  5. Remove the divs
  6. Return the difference of the two widths
function scrollbarWidth() {
    var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
    // Append our div, do our calculation and then remove it
    var w1 = $('div', div).innerWidth();
    div.css('overflow-y', 'scroll');
    var w2 = $('div', div).innerWidth();
    return (w1 - w2);