https://github.com/threespot/freeze-scroll
Prevent scrolling the body element (e.g. when a modal window is open)
https://github.com/threespot/freeze-scroll
Last synced: about 1 year ago
JSON representation
Prevent scrolling the body element (e.g. when a modal window is open)
- Host: GitHub
- URL: https://github.com/threespot/freeze-scroll
- Owner: Threespot
- License: mit
- Created: 2018-03-28T19:41:57.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2020-09-04T20:21:28.000Z (almost 6 years ago)
- Last Synced: 2025-04-11T00:02:37.101Z (about 1 year ago)
- Language: JavaScript
- Homepage: https://threespot.github.io/freeze-scroll/
- Size: 591 KB
- Stars: 2
- Watchers: 3
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Freeze Scroll
[](https://www.npmjs.com/package/@threespot/freeze-scroll)
[](https://travis-ci.org/Threespot/freeze-scroll)
[](https://coveralls.io/github/Threespot/freeze-scroll)
This script provides a cross-browser way of preventing scroll on the body element. A common use case for this is when a modal window is open. Without this script, it’s easy for users to unknowingly scroll the page behind the modal and be disoriented when it’s closed.
Inspired by https://benfrain.com/preventing-body-scroll-for-modals-in-ios/
Note: Once Safari and iOS Safari support the “touch-action” CSS property ([caniuse.com](https://caniuse.com/#feat=css-touch-action)), we can simply toggle a class that adds the following:
```css
.js-no-scroll,
.js-no-scroll body {
overflow: hidden;
touch-action: none;
}
/* Create class to allow scrolling on certain elements, like modal windows */
.allow-scroll { touch-action: auto !important; }
```
## Install
```bash
yarn add @threespot/freeze-scroll
```
## Usage
```js
import scroll from "@threespot/freeze-scroll";
// Disable scrolling
scroll.freeze();
// Enable scrolling
scroll.unfreeze();
```
**NOTE:** Calling `freeze()` or `unfreeze()` will trigger a scroll event. If you have other scroll event listeners, you may want to ignore this event by checking for the `js-no-scroll` class on the `` element.
Example:
```js
window.addEventListener('scroll', () => {
// Ignore scroll events trigger by freeze-scroll
if (document.documentElement.classList.contains('js-no-scroll')) {
return false;
}
// continue with your scroll event handler code
});
```
## License
This is free software and may be redistributed under the terms of the [MIT license](https://github.com/Threespot/freeze-scroll/blob/master/LICENSE.md).
## About Threespot
Threespot is an independent digital agency hell-bent on helping those, and only those, who are committed to helping others. Find out more at [https://www.threespot.com](https://www.threespot.com).
[](https://www.threespot.com)