@rfkhusnutdinov/scroll-lock-manager
v1.0.1
Published
A lightweight JavaScript utility to manage body scroll without layout shifts.
Downloads
4
Maintainers
Readme
ScrollLockManager
A lightweight JavaScript utility to manage body scroll without layout shifts. Automatically detects when scroll is locked, even by other scripts or libraries, and applies compensation to prevent content jumps.
Features
- Automatically detects when body scroll is locked, even by other code or libraries
- Automatically compensates scrollbar width with
margin-rightto prevent content jumps - Overrides any existing
margin-rightset by other libraries for consistent behavior - Supports native
scrollbar-gutterwhen available - Observes
bodyoverflow changes using OverflowObserver - Tracks scrollbar width with ScrollbarWidthObserver
- Lock and unlock scroll programmatically
- Singleton pattern ensures only one instance
Installation
Install from npm
npm install @rfkhusnutdinov/scroll-lock-managerimport ScrollLockManager from "@rfkhusnutdinov/scroll-lock-manager";Use ScrollLockManager from CDN
<script src="https://cdn.jsdelivr.net/npm/@rfkhusnutdinov/scroll-lock-manager@latest"></script>Usage
const scrollManager = new ScrollLockManager({
useScrollbarGutter: true, // optional, default is true
});
// Lock scroll
scrollManager.lockScroll();
// Unlock scroll
scrollManager.unlockScroll();
// Disconnect and clean up
scrollManager.disconnect();Notes
- ScrollLockManager prevents document jumps that usually occur when
overflow: hiddenis applied by compensating the scrollbar width withmargin-right. - The plugin automatically detects when scroll is locked, even if done by other scripts or libraries, and applies the necessary styles to maintain consistent layout.
- Any existing
margin-rightset by other libraries is overridden to ensure correct alignment and prevent layout shifts. - The
useScrollbarGutteroption enables the native CSSscrollbar-gutterproperty if supported by the browser, providing smoother layouts. - CSS classes are applied automatically:
scroll-lock-manager-overflow-hiddenis added when body overflow is hidden. - Singleton pattern ensures only one instance of ScrollLockManager is active at a time.
API
| Method | Description | | --------------------------------------------- | -------------------------------------------------------- | | new ScrollLockManager({ useScrollbarGutter }) | Initializes the manager or returns the existing instance | | lockScroll() | Locks body scroll | | unlockScroll() | Unlocks body scroll | | disconnect() | Stops observing and cleans up styles/observers |
