body-scroll-freezer
Advanced tools
Comparing version 1.0.0 to 1.0.1
@@ -6,3 +6,3 @@ { | ||
"license": "MIT", | ||
"version": "1.0.0", | ||
"version": "1.0.1", | ||
"main": "docs/js/body-scroll-freezer.min.js", | ||
@@ -9,0 +9,0 @@ "homepage": "https://github.com/ramonvictor/body-scroll-freezer/", |
@@ -11,21 +11,30 @@ # body-scroll-freezer | ||
## A note on performance | ||
Many other alternatives to this module listen to both `mousewheel` and `DOMMouseScroll` events in order to get some information from the DOM, which usually includes: `Element.scrollTop`, `event.deltaY`, `Element.scrollHeight` or `Element.clientHeight`. Check this [StackOverflow answer](http://stackoverflow.com/questions/5802467/prevent-scrolling-of-parent-element#answer-16324762) as an example. | ||
The problem is that most of those DOM operations (`.scrollTop` and `.scrollHeight`, for example) are expensive because they [force layout/reflow](https://gist.github.com/paulirish/5d52fb081b3570c81e3a). For more info on scrolling performance [check out this article](https://www.html5rocks.com/en/tutorials/speed/scrolling/). | ||
So, to avoid all that, **body-scroll-freezer** just assigns `overflow: hidden;` and `padding-right: [scrollWidth]px;` to the `<body>`. | ||
The `overflow` avoids vertical move on the background when users are scrolling within the modal box. The `padding-right` prevents horizontal jumps when hiding/showing the scrollbar. | ||
## Usage | ||
```js | ||
var bodyScroll = require('body-scroll-freezer'); // If no AMD/CommonJS: window.bodyScrollFreezer; | ||
// If no AMD/CommonJS: window.bodyScrollFreezer; | ||
var bodyScroll = require('body-scroll-freezer'); | ||
``` | ||
1 - Init to calculate scroll bar width. | ||
1\. Init to calculate scroll bar width. | ||
```js | ||
// Note: store init() return in a variable is optional. | ||
// Note: declaring variable to store init() return is optional. | ||
var scrollWidth = bodyScroll.init(); | ||
``` | ||
2 - Turn scroll freeze **ON** when closing modal. Example: | ||
2\. Turn scroll freeze **ON** when closing modal. Example: | ||
```js | ||
document.querySelector('.modal-open').addEventListener('click', function() { | ||
modal.style.display = 'block'; | ||
// Freeze on modal open | ||
// Logic to show modal goes here | ||
bodyScroll.freeze(); | ||
@@ -35,8 +44,7 @@ }, false); | ||
3 - Turn scroll freeze **OFF** when closing modal. Example: | ||
3\. Turn scroll freeze **OFF** when closing modal. Example: | ||
```js | ||
document.querySelector('.modal-close').addEventListener('click', function() { | ||
modal.style.display = 'none'; | ||
// Unfreeze on modal open | ||
// Logic to hide modal goes here | ||
bodyScroll.unfreeze(); | ||
@@ -43,0 +51,0 @@ }, false); |
28311
66