Created
August 31, 2025 21:28
-
-
Save wesruv/b2659c3100e52c4a299bfe77daf9c6b3 to your computer and use it in GitHub Desktop.
Scrollbar width setter and listener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const setScrollbarWidth = () => { | |
const htmlEl = document.documentElement; | |
const scrollbarWidthLabel = '--scrollbar-width'; | |
let scrollbarWidth; | |
// Get CSS value as an integer, will be set to 0 or a number followed by px, e.g. '20px' | |
const scrollbarWidthValue = | |
htmlEl.style.getPropertyValue(scrollbarWidthLabel).length > 0 ? | |
parseInt(htmlEl.style.getPropertyValue(scrollbarWidthLabel).split('px')[0]) : | |
undefined; | |
// We have vertical scroll | |
if (htmlEl.scrollHeight > htmlEl.clientHeight) { | |
const storedScrollbarWidth = htmlEl.dataset.scrollbarWidth ? parseInt(htmlEl.dataset.scrollbarWidth) : undefined; | |
// Get the scrollbar width once | |
if (typeof storedScrollbarWidth === 'undefined') { | |
// Cheap wayof getting scrollbar width, but is a little faulty | |
scrollbarWidth = window.outerWidth - window.innerWidth; | |
// More expensive way if the faulty way is sus | |
if (scrollbarWidth > 50) { | |
scrollbarWidth = window.innerWidth - htmlEl.offsetWidth; | |
} | |
htmlEl.dataset.scrollbarWidth = scrollbarWidth; | |
} | |
else { | |
scrollbarWidth = storedScrollbarWidth; | |
} | |
// Update if we need to | |
if (scrollbarWidthValue !== scrollbarWidth) { | |
htmlEl.style.setProperty(scrollbarWidthLabel, `${scrollbarWidth}px`); | |
} | |
} | |
else if (scrollbarWidthValue !== 0) { | |
htmlEl.style.setProperty(scrollbarWidthLabel, '0'); | |
} | |
}; | |
setScrollbarWidth(); | |
document.addEventListener('load', setScrollbarWidth); | |
// Backdrop.optimizedResize.add(setScrollbarWidth, 'setScrollbarWidth'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment