How can I determine the height of a horizontal scrollbar, or the width of a vertical one, in JavaScript?
function getWindowScrollBarHeight() {
let bodyStyle = window.getComputedStyle(document.body);
let fullHeight = document.body.scrollHeight;
let contentsHeight = document.body.getBoundingClientRect().height;
let marginTop = parseInt(bodyStyle.getPropertyValue('margin-top'), 10);
let marginBottom = parseInt(bodyStyle.getPropertyValue('margin-bottom'), 10);
return fullHeight - contentHeight - marginTop - marginBottom;
}
window.scrollBarWidth = function() {
document.body.style.overflow = 'hidden';
var width = document.body.clientWidth;
document.body.style.overflow = 'scroll';
width -= document.body.clientWidth;
if(!width) width = document.body.offsetWidth - document.body.clientWidth;
document.body.style.overflow = '';
return width;
}
function getScrollBarWidth() {
return window.innerWidth - document.documentElement.clientWidth;
}
Most of the browser use 15px for the scrollbar width
Using jQuery, you can shorten Matthew Vines answer to:
function getScrollBarWidth () {
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
return 100 - widthWithScroll;
};
The way Antiscroll.js
does it in it's code is:
function scrollbarSize () {
var div = $(
'<div class="antiscroll-inner" style="width:50px;height:50px;overflow-y:scroll;'
+ 'position:absolute;top:-200px;left:-200px;"><div style="height:100px;width:100%"/>'
+ '</div>'
);
$('body').append(div);
var w1 = $(div).innerWidth();
var w2 = $('div', div).innerWidth();
$(div).remove();
return w1 - w2;
};
The code is from here: https://github.com/LearnBoost/antiscroll/blob/master/antiscroll.js#L447
I made an updated version of @Matthew Vines answer.
It's easier to read, easier to understand. It doesn't require an inner element. The element created to get the scroll bar width has a 100% height/width so it doesn't create any visible scroll bar on the body on lower end PCs/mobiles which could take a bit more time to create the element, get the widths, and finally remove the element.
const getScrollBarWidth = () => {
const e = document.createElement('div');
Object.assign(e.style, {
width: '100%',
height: '100%',
overflow: 'scroll',
position: 'absolute',
visibility: 'hidden',
top: '0',
left: '0',
});
document.body.appendChild(e);
const scrollbarWidth = e.offsetWidth - e.clientWidth;
document.body.removeChild(e);
return scrollbarWidth;
};
console.log(getScrollBarWidth());
I do recommend to check for the scroll bar width only once, at page load (except if it doesn't fit your needs) then store the result in a state/variable.