Getting scroll bar width using JavaScript
// offsetWidth includes width of scroll bar and clientWidth doesn't. As rule, it equals 14-18px. so:
var scrollBarWidth = element.offsetWidth - element.clientWidth;
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:
- Create hidden div (outer) and get it's offset width
- Force scroll bars to appear in div (outer) using CSS overflow property
- Create new div (inner) and append to outer, set its width to '100%' and get offset width
- 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).
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;