Skip to content

Instantly share code, notes, and snippets.

@alexmccabe
Created June 21, 2017 19:13
Show Gist options
  • Save alexmccabe/50f6424b2edcac2aeebbb7892dbd63b3 to your computer and use it in GitHub Desktop.
Save alexmccabe/50f6424b2edcac2aeebbb7892dbd63b3 to your computer and use it in GitHub Desktop.
/*global $*/
class ScrollClass {
constructor () {
this.$body = $('body');
this.styles = {
disabled: {
'height': '100%',
'overflow': 'hidden',
},
enabled: {
'height': '',
'overflow': '',
}
};
}
calculateScrollbarWidth () {
let scrollDiv = document.createElement('div');
let container = document.createElement('div');
let scrollbarWidth = 0;
container.appendChild(scrollDiv);
container.style.height = '200px';
container.style.overflowY = 'scroll';
scrollDiv.style.height = '300px';
document.body.appendChild(container);
// Get the scrollbar width
scrollbarWidth = container.offsetWidth - scrollDiv.clientWidth;
// Delete the DIV
document.body.removeChild(container);
return scrollbarWidth;
}
disable ($element = $(window)) {
let disabled = false;
let scrollTop = window.pageYOffset;
$element
.on('scroll.disablescroll', (event) => {
event.preventDefault();
this.$body.css(this.styles.disabled);
window.scrollTo(0, scrollTop);
return false;
})
.on('touchstart.disablescroll', () => {
disabled = true;
})
.on('touchmove.disablescroll', (event) => {
if (disabled) {
event.preventDefault();
}
})
.on('touchend.disablescroll', () => {
disabled = false;
});
}
enable ($element = $(window)) {
$element.off('.disablescroll');
this.$body.css(this.styles.enabled);
}
}
export const Scroll = new ScrollClass();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment