From f86a91d8d12926fc006984e6c523756e8a117df8 Mon Sep 17 00:00:00 2001 From: Valentin Silytuin Date: Tue, 27 Feb 2024 12:14:03 +0400 Subject: [PATCH] v1.1.0 --- README.md | 10 ++++++++++ index.js | 39 +++++++++++++++++++++++---------------- package.json | 2 +- 3 files changed, 34 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index a79b494..1220ade 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,17 @@ # get-scrollbar-width +Get window scrollbar width (if present): + ```js import getScrollbarWidth from '@advdominion/get-scrollbar-width'; console.log(getScrollbarWidth()); ``` + +Get system scrollbar width: + +```js +import getScrollbarWidth from '@advdominion/get-scrollbar-width'; + +console.log(getScrollbarWidth(false)); +``` diff --git a/index.js b/index.js index 0ebd844..e1d80c2 100644 --- a/index.js +++ b/index.js @@ -1,17 +1,24 @@ -export default () => { - if (document.body.clientHeight > window.innerHeight) { - const outer = document.createElement('div'); - outer.style.visibility = 'hidden'; - outer.style.width = '100px'; - document.body.append(outer); - const widthNoScroll = outer.offsetWidth; - outer.style.overflow = 'scroll'; - const inner = document.createElement('div'); - inner.style.width = '100%'; - outer.append(inner); - const widthWithScroll = inner.offsetWidth; - outer.remove(); - return widthNoScroll - widthWithScroll; - } - return 0; +const scrollbarWidth = () => { + const outer = document.createElement('div'); + outer.style.visibility = 'hidden'; + outer.style.width = '100px'; + document.body.append(outer); + const widthNoScroll = outer.offsetWidth; + outer.style.overflow = 'scroll'; + const inner = document.createElement('div'); + inner.style.width = '100%'; + outer.append(inner); + const widthWithScroll = inner.offsetWidth; + outer.remove(); + return widthNoScroll - widthWithScroll; +}; + +export default (getWindowScrollbar = true) => { + if (getWindowScrollbar) { + if (document.body.clientHeight > window.innerHeight) { + return scrollbarWidth(); + } + return 0; + } + return scrollbarWidth(); }; diff --git a/package.json b/package.json index 48050a1..b6273e1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@advdominion/get-scrollbar-width", - "version": "1.0.0", + "version": "1.1.0", "type": "module", "main": "index.js", "repository": {