Last active
August 28, 2025 09:33
-
-
Save Rican7/bf0dbcc5e41b52805b32263dc20d2d1f to your computer and use it in GitHub Desktop.
Get web browser scrollbar dimensions
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
export class ScrollDimensions { | |
#parentContext?: HTMLElement; | |
#barWidth: number = 0; | |
#barNormalWidth: number = 0; | |
#barThinWidth: number = 0; | |
constructor(parentContext?: HTMLElement) { | |
if (typeof document === 'undefined') { | |
return; | |
} | |
this.#parentContext = parentContext ?? document.body; | |
this.#measureDimensions(); | |
} | |
get scrollbarWidth() { | |
return this.#barWidth; | |
} | |
get scrollbarNormalWidth() { | |
return this.#barNormalWidth; | |
} | |
get scrollbarThinWidth() { | |
return this.#barThinWidth; | |
} | |
#measureDimensions() { | |
if (!this.#parentContext) { | |
return; | |
} | |
// Add temporary box to wrapper | |
const scrollbox = document.createElement('div'); | |
// Make box scrollable | |
scrollbox.style.overflow = 'scroll'; | |
// Append box to document | |
this.#parentContext.appendChild(scrollbox); | |
scrollbox.style.scrollbarWidth = 'inherit'; | |
this.#barWidth = this.#measureScrollbarWidths(scrollbox); | |
scrollbox.style.scrollbarWidth = 'auto'; | |
this.#barNormalWidth = this.#measureScrollbarWidths(scrollbox); | |
scrollbox.style.scrollbarWidth = 'thin'; | |
this.#barThinWidth = this.#measureScrollbarWidths(scrollbox); | |
// Remove box | |
this.#parentContext.removeChild(scrollbox); | |
} | |
#measureScrollbarWidths(element: HTMLElement): number { | |
return element.offsetWidth - element.clientWidth; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment