11

Get the Width of Scrollbar Using JavaScript

 3 years ago
source link: https://pineco.de/snippets/get-the-width-of-scrollbar-using-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Get the Width of Scrollbar Using JavaScript

It can be handy to know the width of the scrollbar. A frequent example can be a modal. In a case of a modal, we usually want to disable the outside scroll on the body element. For this, we add overflow: hidden; to the body, the scrollbar will disappear, and our content will shift into its place.

Get the Width of the Browser Scrollbar

This shift is annoying, and one way to avoid it to add an offset (when the overflow hidden is present) to the right side of theelement. For this, we must get the current width of the scrollbar. If you want to get the browser’s scrollbar width, you can use the following:


function getBrwoserScrollbarWidth() {
  return window.innerWidth - document.documentElement.clientWidth;
}

With the window.innerWidth, we will get the width of the browser. Width the document.documentElement.clientWidth we will get the width of our document (without the scrollbar). If we subtract them from each other, we will get the scrollbar width.

Get the Width of the Scrollbar on Any Element

We can also measure the scrollbar width on any element with a slightly modification. Insted of using the window object we need to get the element.offsetWidth:


function getElementScrollbarWidth(element) {
    return element.offsetWidth - element.clientWidth;
}

getElementScrollbarWidth(document.querySelector('.custom-element'));

Need a web developer? Maybe we can help, get in touch!

To see and write comments, you must allow the related (Disqus) cookies. For more information, please visit our privacy policy page.

Need a reliable, small web developer team? Try us! We develop with Laravel and Vue.js.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK