Skip to content

Instantly share code, notes, and snippets.

@remydagostino
Last active December 21, 2015 18:39
Show Gist options
  • Save remydagostino/6348814 to your computer and use it in GitHub Desktop.
Save remydagostino/6348814 to your computer and use it in GitHub Desktop.
Calculate the width of the browser scrollbars. Credit: http://davidwalsh.name/detect-scrollbar-width
var getScrollbarWidth = function() {
var scrollbarWidth;
return (function() {
if (scrollbarWidth) {
return scrollbarWidth;
}
// Create the measurement node
var scrollDiv = document.createElement("div");
// Presumably no browsers have scroll bars wider than 100px!
scrollDiv.style.width = "100px"
scrollDiv.style.height = "100px";
scrollDiv.style.overflow = "scroll";
// Position it off the screen
scrollDiv.style.position = "absolute";
scrollDiv.style.top = "-9999px";
document.body.appendChild(scrollDiv);
// Get the scrollbar width
scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
// Delete the DIV
document.body.removeChild(scrollDiv);
return scrollbarWidth;
})();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment