snippetjavascriptTip
Get the width of the scrollbar using JavaScript
Viewed 0 times
javascriptwidthscrollbargettheusing
Problem
When working in a browser environment, it's often needed to calculate the width of the vertical scrollbar. This is useful when you want to calculate the width of the window without the scrollbar, or when you want to adjust the width of an element to account for the scrollbar.
Luckily, it only takes a little bit of math, once you understand how to get the necessary values. First, we need to get the width of the whole window, which can be accomplished with
Luckily, it only takes a little bit of math, once you understand how to get the necessary values. First, we need to get the width of the whole window, which can be accomplished with
Window.innerWidth. Then, we need to get the width of the Document element, which can be done using Element.clientWidth. Finally, we subtract the two values to get the width of the vertical scrollbar.Solution
const getScrollbarWidth = () =>
window.innerWidth - document.documentElement.clientWidth;
getScrollbarWidth(); // 15Code Snippets
const getScrollbarWidth = () =>
window.innerWidth - document.documentElement.clientWidth;
getScrollbarWidth(); // 15Context
From 30-seconds-of-code: get-scrollbar-width
Revisions (0)
No revisions yet.