Detect width of Scrollbar

Asked

Viewed 72 times

0

To leave well structured a page that will have the scrollbar disabled when a certain button is clicked, I think about setting an additional padding to the body com js, to compensate for the hidden scroll. I’ve been reading around that many browsers already have a standard width of 17px, but others have different specifications. What I need is a solution to detect the width of the native document scrollbar, take that value and add to the body.

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

1 answer

1


Get the width of scroll

Through this reply I saw that it is possible to create a div hidden, other div within it with scroll and through the difference of the two know what is the width of the scroll used by the browser.

That 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());

  • I am using the latest version of firefox. 60.0.1, on the console is giving this error: TypeError: document.body is null

  • Your tag <script> is at the end of tag body? , this error may be causing because the script is running before loading the full HTML.

  • Wow. What a detail! Now it worked. Thx.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.