handle multiple body scroll lockers

This commit is contained in:
taehoon 2019-10-17 16:03:41 -04:00
parent 8db1fa506c
commit 093d785fbf

View File

@ -2,13 +2,18 @@ import * as bodyScrollLock from 'body-scroll-lock'
let previousNavPaddingRight let previousNavPaddingRight
let previousAppBgWrapperRight let previousAppBgWrapperRight
let lockerEls = []
const disableBodyScroll = (el) => { const disableBodyScroll = (el) => {
const scrollBarGap = window.innerWidth - document.documentElement.clientWidth const scrollBarGap = window.innerWidth - document.documentElement.clientWidth
bodyScrollLock.disableBodyScroll(el, { bodyScrollLock.disableBodyScroll(el, {
reserveScrollBarGap: true reserveScrollBarGap: true
}) })
if (!lockerEls.includes(el)) {
lockerEls.push(el)
}
setTimeout(() => { setTimeout(() => {
if (lockerEls.length <= 1) {
// If previousNavPaddingRight is already set, don't set it again. // If previousNavPaddingRight is already set, don't set it again.
if (previousNavPaddingRight === undefined) { if (previousNavPaddingRight === undefined) {
const navEl = document.getElementById('nav') const navEl = document.getElementById('nav')
@ -22,11 +27,16 @@ const disableBodyScroll = (el) => {
appBgWrapperEl.style.right = previousAppBgWrapperRight ? `calc(${previousAppBgWrapperRight} + ${scrollBarGap}px)` : `${scrollBarGap}px` appBgWrapperEl.style.right = previousAppBgWrapperRight ? `calc(${previousAppBgWrapperRight} + ${scrollBarGap}px)` : `${scrollBarGap}px`
} }
document.body.classList.add('scroll-locked') document.body.classList.add('scroll-locked')
}
}) })
} }
const enableBodyScroll = (el) => { const enableBodyScroll = (el) => {
if (lockerEls.includes(el)) {
lockerEls = lockerEls.filter(e => e !== el)
}
setTimeout(() => { setTimeout(() => {
if (!lockerEls.length) {
if (previousNavPaddingRight !== undefined) { if (previousNavPaddingRight !== undefined) {
document.getElementById('nav').style.paddingRight = previousNavPaddingRight document.getElementById('nav').style.paddingRight = previousNavPaddingRight
// Restore previousNavPaddingRight to undefined so disableBodyScroll knows it can be set again. // Restore previousNavPaddingRight to undefined so disableBodyScroll knows it can be set again.
@ -38,6 +48,7 @@ const enableBodyScroll = (el) => {
previousAppBgWrapperRight = undefined previousAppBgWrapperRight = undefined
} }
document.body.classList.remove('scroll-locked') document.body.classList.remove('scroll-locked')
}
}) })
bodyScrollLock.enableBodyScroll(el) bodyScrollLock.enableBodyScroll(el)
} }