Created
July 13, 2021 13:55
-
-
Save fedorenkodev/efb6367faab40dae1c2ae3fe3b728119 to your computer and use it in GitHub Desktop.
Get scrollbar width (VanillaJS & jQuery)
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
// jQuery | |
export const getScrollbarWidth = () => { | |
// Creating invisible container | |
const outer = document.createElement('div'); | |
outer.style.visibility = 'hidden'; | |
outer.style.overflow = 'scroll'; // forcing scrollbar to appear | |
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps | |
document.body.appendChild(outer); | |
// Creating inner element and placing it in the container | |
const inner = document.createElement('div'); | |
outer.appendChild(inner); | |
// Calculating difference between container's full width and the child width | |
const scrollbarWidth = outer.offsetWidth - inner.offsetWidth; | |
// Removing temporary elements from the DOM | |
outer.parentNode.removeChild(outer); | |
return scrollbarWidth; | |
} | |
// VanillaJS | |
export const getScrollBarWidth = () => { | |
// Creating invisible container | |
const outer = document.createElement('div'); | |
outer.style.visibility = 'hidden'; | |
outer.style.overflow = 'scroll'; // forcing scrollbar to appear | |
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps | |
document.body.appendChild(outer); | |
// Creating inner element and placing it in the container | |
const inner = document.createElement('div'); | |
outer.appendChild(inner); | |
// Calculating difference between container's full width and the child width | |
const scrollbarWidth = outer.offsetWidth - inner.offsetWidth; | |
// Removing temporary elements from the DOM | |
outer.parentNode.removeChild(outer); | |
return scrollbarWidth; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment