For example: how do I get the width of the browser scrollbar from JS?

Add a 200 pixels high and 100 pixels wide div to the body tag and set overflow property to Scroll. Then the scroll bar will appear to the right and bottom of the div. Dynamically insert a div element with a width of 100% into the div tag and take the offsetWidth value of the two to get the width of the scroll bar.

Here is the code implementation

const getScrollBarWidth = () => {
  const outer = document.createElement('div');
  outer.style.overflow = 'scroll';
  outer.style.height='200px';
  outer.style.width = '100px';
  document.body.appendChild(outer);
  const widthNoScroll = outer.offsetWidth;

  console.log('widthNoScroll', widthNoScroll)

  const inner = document.createElement('div');
  inner.style.width = '100%';
  outer.appendChild(inner);

  const widthWithScroll = inner.offsetWidth;

  console.log('widthWithScroll', widthWithScroll)

  scrollBarWidth = widthNoScroll - widthWithScroll;

  console.log(scrollBarWidth)

  return scrollBarWidth;
}
getScrollBarWidth();
Copy the code

Console output in the browser