To get the width of the scrollbar, you use the offsetWidth
and clientWidth
of the Element
:
- The
offsetWidth
returns the width of theElement
in pixels including the scrollbar. - The
clientWidth
returns the with of theElement
in pixels without the scrollbar.
So to get the width of the scrollbar, you just need to carry a simple calculation as follows:
const box = document.querySelector('.box');
const scrollbarWidth = box.offsetWidth - box .clientWidth;
Code language: JavaScript (javascript)
The following returns the scrollbar width of the document:
const scrollbarWidth = document.body.offsetWidth - document.body.clientWidth;
Code language: JavaScript (javascript)
Was this tutorial helpful ?