To get the width of the scrollbar, you use the offsetWidth and clientWidth of the Element:
- The
offsetWidthreturns the width of theElementin pixels including the scrollbar. - The
clientWidthreturns the with of theElementin 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 ?