@rfkhusnutdinov/scrollbar-width-observer
v2.0.0
Published
JavaScript plugin to monitor scrollbar width and update a CSS variable.
Maintainers
Readme
ScrollbarWidthObserver
A lightweight JavaScript plugin to monitor changes in the scrollbar width.
Automatically updates a CSS variable and dispatches a scrollbarwidthchange event on changes.
Features
- Observes scrollbar width changes on window resize
- Updates a CSS variable (default
--scrollbar-width) with the current width - Dispatches a custom
scrollbarwidthchangeevent - Singleton pattern ensures only one observer instance
- Debounced resize handling to optimize performance
Installation
Install from npm
npm install @rfkhusnutdinov/scrollbar-width-observerimport ScrollbarWidthObserver from "@rfkhusnutdinov/scrollbar-width-observer";Use ScrollbarWidthObserver from CDN
<script src="https://cdn.jsdelivr.net/npm/@rfkhusnutdinov/scrollbar-width-observer@latest"></script>Usage
const observer = ScrollbarWidthObserver.getInstance({
cssVariableName: "--scrollbar-width", // optional, default is --scrollbar-width
});
// Get scrollbar width value
const scrollbarWidthValue = observer.scrollbarWidth;
// Listen for scrollbar width changes
window.addEventListener("scrollbarwidthchange", (event) => {
console.log("Scrollbar width changed to:", event.detail.scrollbarWidth);
});
// Disconnect observer when no longer needed
observer.disconnect();Notes
- The plugin calculates the scrollbar width using a temporary DOM element.
- CSS variable is applied to body for easy usage in styles.
- Singleton pattern ensures only one instance is active at a time.
API
| Method | Description | | ----------------------------------------------- | ----------------------------------------------------------------- | | new ScrollbarWidthObserver({ cssVariableName }) | Initializes the observer or returns the existing instance | | disconnect() | Stops observing, removes CSS variable, and cleans up the instance |
