Skip to content

Instantly share code, notes, and snippets.

@scsskid
Created October 22, 2023 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scsskid/f55cdbe10b004965c6c85f61b9f1c860 to your computer and use it in GitHub Desktop.
Save scsskid/f55cdbe10b004965c6c85f61b9f1c860 to your computer and use it in GitHub Desktop.
getScrollBarWidth
export default function getScrollbarWidth() {
// Creating invisible container
const outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.overflow = "scroll"; // forcing scrollbar to appear
// @ts-ignore
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
if (outer.parentNode) {
outer.parentNode.removeChild(outer);
}
return scrollbarWidth;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment