feat: prevent scrolling the rest of the page when a modal is open #1617

Merged
konrad merged 2 commits from feature/stop-body-scrolling-when-modal-is-open into main 2022-03-27 20:42:21 +00:00
1 changed files with 7 additions and 19 deletions
Showing only changes of commit f92aeed540 - Show all commits

View File

@ -8,6 +8,7 @@
{ 'has-overflow': overflow },
variant,
]"
ref="modal"
>
<div
class="modal-container"
@ -62,7 +63,8 @@
<script lang="ts" setup>
import BaseButton from '@/components/base/BaseButton.vue'
import {onUnmounted, watch} from 'vue'
import {ref, watch} from 'vue'
import {useScrollLock} from '@vueuse/core'
const props = withDefaults(defineProps<{
enabled?: boolean,
@ -76,34 +78,20 @@ const props = withDefaults(defineProps<{
variant: 'default',
})
defineEmits(['close', 'submit'])
defineEmits(['close', 'submit'])
// Based on https://css-tricks.com/prevent-page-scrolling-when-a-modal-is-open/
function resetScrolling() {
const body = document.body
const scrollY = body.style.top
body.style.position = ''
body.style.top = ''
window.scrollTo(0, parseInt(scrollY || '0') * -1)
}
const modal = ref<HTMLElement | null>(null)
Review

Why not:

const modal = ref<HTMLElement>()
Why not: ```js const modal = ref<HTMLElement>() ```
Review

Don't I need to specify the default value?

Don't I need to specify the default value?
Review

The default would be undefined in that case. Meaning:

ref<HTMLElement>() is identical to ref<HTMLElement | undefined>(undefined)

The default would be `undefined` in that case. Meaning: `ref<HTMLElement>()` is identical to `ref<HTMLElement | undefined>(undefined)`
Review

Ohh okay, that makes sense. I'm kind of used to setting everything to null if its not defined, coming from the backend. But undefined makes more sense in the js world.

Ohh okay, that makes sense. I'm kind of used to setting everything to `null` if its not defined, coming from the backend. But `undefined` makes more sense in the js world.
const scrollLock = useScrollLock(modal)
watch(
() => props.enabled,
enabled => {
if (enabled) {
const scrollY = window.scrollY
document.body.style.position = 'fixed'
document.body.style.top = `-${scrollY}px`
} else {
resetScrolling()
}
scrollLock.value = enabled
},
{
immediate: true,
},
)
onUnmounted(resetScrolling)
</script>
<style lang="scss" scoped>