Created
June 30, 2019 04:31
-
-
Save nicholasxjy/9f304893f4c660952ea7a68bf726bb35 to your computer and use it in GitHub Desktop.
prevent-body-scroll
This file contains 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
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