Sometimes, we want to get scroll bar width using JavaScript.
In this article, we’ll look at how to get scroll bar width using JavaScript.
How to get scroll bar width using JavaScript?
To get scroll bar width using JavaScript, we can subtract the scrolling element’s width by the immediate child’s width.
For instance, we write
const child = document.querySelector("div");
const scrollbarWidth = child.parentNode.offsetWidth - child.offsetWidth;
to get the scroll container’s width with child.parentNode.offsetWidth
.
Then we get the child div’s width with child.offsetWidth
.
And then we subtract the scroll container’s width with the div’s width to get the scroll bar’s width.
Conclusion
To get scroll bar width using JavaScript, we can subtract the scrolling element’s width by the immediate child’s width.