Categories
JavaScript Answers

How to get scroll bar width using JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *