How can I determine the height of a horizontal scrollbar, or the width of a vertical one, in JavaScript?
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.