0

I removed the body scrollbar and then must compensate for its lack with padding. To do this, I try to calculate the width of the scrollbar of the div block that appears after removing the body scrollbar and pass the resulting value as padding. This works in Chrome, but does not work in other browsers. Here is my code:

element = document.getElementById('div');
var scrollBarWidth = element.offsetWidth - element.clientWidth;
  document.body.style.paddingRight = scrollBarWidth + 'px';

I would really appreciate a suitable solution.

Goga
  • 9
  • 5
  • 1
    Does this answer your question? [How can I get the browser's scrollbar sizes?](https://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes) – imvain2 Jun 02 '20 at 19:19
  • I seem to be confused ... I deleted the scrollbar from the body and should add padding instead of the scrollbar, but then how to calculate the width of the scrollbar if I deleted it. The div block that appears after removing the body scrollbar may not have a scrollbar and therefore I still cannot get the width. – Goga Jun 02 '20 at 19:32
  • I can compensate for the removal of the scrollbar in the body by adding a class with the appropriate css to the body, but the width of the scrollbar in different browsers can be different. – Goga Jun 02 '20 at 19:36

1 Answers1

0

It seems to work, but maybe there is a simpler solution that works in all browsers?

// Create the measurement node
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);

// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
console.info(scrollbarWidth); // Mac:  15

// Delete the DIV 
document.body.removeChild(scrollDiv);
.scrollbar-measure {
 width: 100px;
 height: 100px;
 overflow: scroll;
 position: absolute;
 top: -9999px;
}
document.body.style.paddingRight = (scrollbarWidth) + 'px';
Goga
  • 9
  • 5