Detect width of Scrollbar

0

To make a page that has scrollbar disabled when a particular button is clicked, I plan to set an additional padding to the body with js to compensate for the hidden scroll. I've been reading around so many browsers already have a default width of 17px, but others have different specifications. What I need is a solution to detect the width of the native scrollbar document, grab this value and add it to the body.

$('body').css('padding-right', WidthDoScrollbar);

    
asked by anonymous 28.05.2018 / 15:51

1 answer

1

Get the width of scroll

Through this response I saw that it is possible to create a% hidden% , another% with_in% of it with scroll and through the difference of the two know the width of the scroll used by the browser.

This is the code:

function getScrollbarWidth() {
    var outer = document.createElement("div");
    outer.style.visibility = "hidden";
    outer.style.width = "100px";
    outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps

    document.body.appendChild(outer);

    var widthNoScroll = outer.offsetWidth;
    // force scrollbars
    outer.style.overflow = "scroll";

    // add innerdiv
    var inner = document.createElement("div");
    inner.style.width = "100%";
    outer.appendChild(inner);        

    var widthWithScroll = inner.offsetWidth;

    // remove divs
    outer.parentNode.removeChild(outer);

    return widthNoScroll - widthWithScroll;
}

console.log(getScrollbarWidth());
    
28.05.2018 / 16:55