How to get the scrollbar width of an element using JavaScript

published: 18 May 2022

2 min read

How to get the scrollbar width of an element using JavaScript

To get the scrollbar width of an HTML element, you can use the offsetWidth and clientWidth property of the element.

The offsetWidth returns the width of the element in pixels, including the scrollbar. On the other hand, the clientWidth property returns the width of the element without scrollbar.

All you need to do is carry a simple calculation to get the actual scrollbar width:

const div = document.querySelector('.pizza')

const scrollbarWidth = div.offsetWidth - div.clientWidth

To get the scrollbar width of the document, you can use the following code:

const scrollbarWidth = document.body.offsetWidth - document.body.clientWidth

How to get the scrollbar width of an element using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming