Last active
January 15, 2017 02:03
-
-
Save ramonvictor/0a9b3a786ce0e8c37fead97fbfcf044f to your computer and use it in GitHub Desktop.
Module to freeze body scroll without horizontal alignment glitch due to browser default behaviour (hidding scroll bar).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.js-scrollbar-measure { | |
width: 100px; | |
height: 100px; | |
overflow: scroll; | |
position: absolute; | |
top: -9999px; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var events = require('eventBus'); | |
var MEASURE_SCROLL_CLASSS = 'js-scrollbar-measure'; | |
var body = document.body; | |
var scrollWidth; | |
function initListeners() { | |
scrollWidth = getScrollWidth(); | |
events.on('freeze-body-scroll:freeze', freeze); | |
events.on('freeze-body-scroll:unfreeze', unfreeze); | |
} | |
function freeze(data) { | |
body.style.overflow = 'hidden'; | |
body.style.paddingRight = scrollWidth + 'px'; | |
events.emit('freeze-body-scroll:freeze-on', { scrollWidth: scrollWidth }); | |
} | |
function unfreeze(data) { | |
body.style.overflow = 'auto'; | |
body.style.paddingRight = '0px'; | |
events.emit('freeze-body-scroll:freeze-off', { scrollWidth: scrollWidth }); | |
} | |
function getScrollWidth() { | |
var div = document.createElement('div'); | |
var scrollBarWidth; | |
div.className = MEASURE_SCROLL_CLASSS; | |
body.appendChild(div); | |
scrollBarWidth = div.offsetWidth - div.clientWidth; | |
body.removeChild(div); | |
return scrollBarWidth; | |
} | |
exports.initListeners = initListeners; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment