Skip to content

Instantly share code, notes, and snippets.

@nicholasxjy
Created June 30, 2019 04:31
Show Gist options
  • Save nicholasxjy/9f304893f4c660952ea7a68bf726bb35 to your computer and use it in GitHub Desktop.
Save nicholasxjy/9f304893f4c660952ea7a68bf726bb35 to your computer and use it in GitHub Desktop.
prevent-body-scroll
let previousOverflow
let previousPaddingRight
/**
* Toggle the body scroll / overflow and additional styling
* necessary to preserve scroll position and body width (scrollbar replacement)
*
* @param {boolean} preventScroll - whether or not to prevent body scrolling
*/
export default function preventBodyScroll(preventScroll) {
/** Get the width before toggling the style so we can calculate the scrollbar width for a smooth, jankless style change */
const { width } = document.body.getBoundingClientRect()
/** Apply or remove overflow style */
if (preventScroll) {
previousOverflow = document.body.style.overflow
document.body.style.overflow = 'hidden'
} else {
document.body.style.overflow = previousOverflow || ''
}
/** Get the _new width_ of the body (this will tell us the scrollbar width) */
const newWidth = document.body.getBoundingClientRect().width
const scrollBarWidth = newWidth - width
/** If there's a diff due to scrollbars, then account for it with padding */
if (preventScroll) {
previousPaddingRight = document.body.style.paddingRight
document.body.style.paddingRight = Math.max(0, scrollBarWidth || 0) + 'px'
} else {
document.body.style.paddingRight = previousPaddingRight || ''
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment