How to know if the scrollbar is active and its size?

2

I have a menu that opens based on the X and Y coordinates of the click , but when it was opened at the ends it ended up extrapolating the layout, I set it up, but when the scrollbar side is active it finishes extrapolating some pixels (probably in% w / o% as well), because% w /% does not take the difference of scroll size, eg ...

when scroll is not active height

When scrolling is active window.innerWidth

In other words, depending on the platform, the average scroll can have a width of up to 15 / 20px, I need to detect when the Scrollbar is active and when I activate its size to subtract this difference,     

asked by anonymous 06.12.2017 / 19:58

1 answer

1

Whether you have scroll

To find out if the window has scroll simply compare the height of the document with the size of the window.

See this code and modify the height of div to see that it identifies when it has scroll :

let doc = $(document).height();
let win = $(window).height();

if(doc > win){
  console.log('Tem scroll');
} else {
  console.log('Não tem scroll');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><divstyle="background-color: lightgreen; height: 500px;"></div>

If you want with pure JavaScript:

let body = document.body, html = document.documentElement;

let docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);

let winHeight = window.innerHeight;

if (docHeight > winHeight){
  console.log('Tem Scroll');
} else {
  console.log('Não tem Scroll');
}
<div style="background-color: lightgreen; height: 100px;"></div>

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());
    
07.12.2017 / 13:06