Getting scroll bar width using JavaScript [duplicate]

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 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).


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

 var scrollBarWidth = element.offsetWidth - element.clientWidth;

I think this will be simple and fast -

var scrollWidth= window.innerWidth-$(document).width()

If the child takes the full width of the container excluding scrollbar (the default), then you can subtract the widths:

var child = document.querySelector(".somethingBig");
var scrollbarWidth = child.parentNode.offsetWidth - child.offsetWidth;

If you use jquery.ui, try this code:

$.position.scrollbarWidth()