Last active
April 23, 2020 08:45
-
-
Save reecelucas/951d7091e706c32002d88dc294aa1c09 to your computer and use it in GitHub Desktop.
Utility functions to toggle page 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 bodyBlocked = false; | |
const { body, documentElement: html } = document; | |
export const blockScroll = () => { | |
if (bodyBlocked) { | |
return; | |
} | |
const scrollBarWidth = window.innerWidth - html.clientWidth; | |
const bodyPaddingRight = | |
parseInt(window.getComputedStyle(body).getPropertyValue("padding-right")) || 0; | |
// 1. Fixes a bug in iOS and desktop Safari whereby setting `overflow: hidden` on | |
// the html/body does not prevent scrolling. | |
// 2. Fixes a bug in desktop Safari where `overflowY` does not prevent scroll if an | |
// `overflow-x` style is also applied to the body. | |
html.style.position = "relative"; // [1] | |
html.style.overflow = "hidden"; // [2] | |
body.style.position = "relative"; // [1] | |
body.style.overflow = "hidden"; // [2] | |
body.style.paddingRight = `${bodyPaddingRight + scrollBarWidth}px`; | |
bodyBlocked = true; | |
}; | |
export const allowScroll = () => { | |
if (!bodyBlocked) { | |
return; | |
} | |
html.style.position = ""; | |
html.style.overflow = ""; | |
body.style.position = ""; | |
body.style.overflow = ""; | |
body.style.paddingRight = ""; | |
bodyBlocked = false; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment