Modal: Delete blur background and handle scrollbar

This commit is contained in:
Lucas Larroche 2021-11-14 11:09:58 +07:00
parent 3d2bc1f911
commit d9a6ac1a65
24 changed files with 221 additions and 390 deletions

View file

@ -9,8 +9,10 @@
const isOpenClass = 'modal-is-open';
const openingClass = 'modal-is-opening';
const closingClass = 'modal-is-closing';
const animationDuration = 400; // ms
let visibleModal = null;
// Toggle modal
const toggleModal = event => {
event.preventDefault();
@ -26,11 +28,14 @@ const isModalOpen = modal => {
// Open modal
const openModal = modal => {
if (isScrollbarVisible()) {
document.documentElement.style.setProperty('--scrollbar-width', `${getScrollbarWidth()}px`);
}
document.documentElement.classList.add(isOpenClass, openingClass);
setTimeout(() => {
visibleModal = modal;
document.documentElement.classList.remove(openingClass);
}, 200);
}, animationDuration);
modal.setAttribute('open', true);
}
@ -40,8 +45,9 @@ const closeModal = modal => {
document.documentElement.classList.add(closingClass);
setTimeout(() => {
document.documentElement.classList.remove(closingClass, isOpenClass);
document.documentElement.style.removeProperty('--scrollbar-width');
modal.removeAttribute('open');
}, 200);
}, animationDuration);
}
// Close with a click outside
@ -58,4 +64,32 @@ document.addEventListener('keydown', event => {
if (event.key === 'Escape' && visibleModal != null) {
closeModal(visibleModal);
}
});
});
// Get scrollbar width
const getScrollbarWidth = () => {
// Creating invisible container
const outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.overflow = 'scroll'; // forcing scrollbar to appear
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
document.body.appendChild(outer);
// Creating inner element and placing it in the container
const inner = document.createElement('div');
outer.appendChild(inner);
// Calculating difference between container's full width and the child width
const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);
// Removing temporary elements from the DOM
outer.parentNode.removeChild(outer);
return scrollbarWidth;
}
// Is scrollbar visible
const isScrollbarVisible = () => {
return document.body.scrollHeight > screen.height;
}