Getting scroll bar width using JavaScript

127

The following HTML will display a scroll bar on the right inside edge of div.container.

Is it possible to determine the width of that scroll bar?

<div class="container" style="overflow-y:auto; height:40px;">
  <div class="somethingBig"></div>
</div>

This question is tagged with javascript

~ Asked on 2012-11-14 16:06:41

The Best Answer is


256

This function should give you width of scrollbar

function getScrollbarWidth() {

  // Creating invisible container
  const outer = document.createElement('div');
  outer.style.visibility = 'hidden';
  outer.style.overflow = 'scroll'; // forcing scrollbar to appear
  outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
  document.body.appendChild(outer);

  // Creating inner element and placing it in the container
  const inner = document.createElement('div');
  outer.appendChild(inner);

  // Calculating difference between container's full width and the child width
  const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);

  // Removing temporary elements from the DOM
  outer.parentNode.removeChild(outer);

  return scrollbarWidth;

}

Basic steps here are:

  1. Create hidden div (outer) and get it's offset width
  2. Force scroll bars to appear in div (outer) using CSS overflow property
  3. Create new div (inner) and append to outer, set its width to '100%' and get offset width
  4. Calculate scrollbar width based on gathered offsets

Working example here: http://jsfiddle.net/slavafomin/tsrmgcu9/

Update

If you're using this on a Windows (metro) App, make sure you set the -ms-overflow-style property of the 'outer' div to scrollbar, otherwise the width will not be correctly detected. (code updated)

Update #2 This will not work on Mac OS with the default "Only show scrollbars when scrolling" setting (Yosemite and up).

~ Answered on 2012-11-14 16:25:54


47

// offsetWidth includes width of scroll bar and clientWidth doesn't. As rule, it equals 14-18px. so:

 var scrollBarWidth = element.offsetWidth - element.clientWidth;

~ Answered on 2016-11-12 23:11:51


Most Viewed Questions: