Last active
March 16, 2026 19:24
-
-
Save wesruv/b2659c3100e52c4a299bfe77daf9c6b3 to your computer and use it in GitHub Desktop.
Scrollbar width setter and listener - has Backrop utility functions
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
| /** | |
| * Gets the width of the scrollbar and sets it to a CSS Custom Property | |
| */ | |
| 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'); | |
| } | |
| } | |
| document.addEventListener('DOMContentLoaded', setScrollbarWidth); | |
| document.addEventListener('load', () => { | |
| setScrollbarWidth(); | |
| // Add a coarse resize listener to update the scrollbar width | |
| // (essentially if there is one or not, and if so, how wide) | |
| const debouncedCallback = Backdrop.debounce(setScrollbarWidth, 1000); | |
| window.addEventListener('resize', debouncedCallback); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment