Scrollbar width in JavaScript

The width of the scrollbar depends on the browser. We can get the value of this width. To do this, we create an element with scrolling, but without borders and padding:

let div = document.createElement('div');

Let's add some styles to it:

div.style.overflowY = 'scroll'; div.style.width = '50px'; div.style.height = '50px';

Let's insert the element into the document, otherwise the dimensions will be zero:

document.body.append(div);

We get the size of the scrollbar:

let scrollWidth = div.offsetWidth - div.clientWidth;

And delete an element:

div.remove();

Given a button. On button click, get the width of the scrollbar in your browser.

enru