Skip to content

Instantly share code, notes, and snippets.

@justinhough
Created January 28, 2022 20:53
Show Gist options
  • Save justinhough/b3252ea3d74a02a1b2fb5dd15346431f to your computer and use it in GitHub Desktop.
Save justinhough/b3252ea3d74a02a1b2fb5dd15346431f to your computer and use it in GitHub Desktop.
Scroll Lock
// Borrowed from https://markus.oberlehner.net/blog/simple-solution-to-prevent-body-scrolling-on-ios/
// Tweaks made to html element for mobile device cases.
const body = document.querySelector('body');
const html = document.querySelector('html');
let scrollPosition = 0;
function enableScrollLock() {
scrollPosition = window.pageYOffset;
body.style.overflow = 'hidden';
body.style.position = 'fixed';
body.style.top = `-${scrollPosition}px`;
body.style.width = '100%';
html.style.height = '100vh';
};
function disableScrollLock() {
body.style.removeProperty('overflow');
body.style.removeProperty('position');
body.style.removeProperty('top');
body.style.removeProperty('width');
html.style.removeProperty('height');
window.scrollTo(0, scrollPosition);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment