UNPKG

natura11y

Version:

Natura11y is an open-source design system for creating beautiful web interfaces with a focus on accessible interaction design and front-end development.

61 lines (41 loc) 1.44 kB
/* In this file: // A. Overlay Open and Close */ import { focusTrap } from './focus.js'; ////////////////////////////////////////////// // A. Overlay Open and Close ////////////////////////////////////////////// let scrollPosition = 0; let rootElement; let lastFocusedElement; // SSR guard if (typeof document !== 'undefined') { rootElement = document.querySelector(':root'); } export const handleOverlayOpen = (element, triggerElement = null, firstFocusTarget = null) => { lastFocusedElement = triggerElement || document.activeElement; scrollPosition = window.scrollY; rootElement.style.setProperty('--scroll-position', `-${scrollPosition}px`); rootElement.classList.add('has-overlay'); if(element) { focusTrap(element, firstFocusTarget ?? element); } } export const handleOverlayClose = (element) => { rootElement.style.removeProperty('--scroll-position'); if(!rootElement.getAttribute('style')) { rootElement.removeAttribute('style'); } rootElement.classList.remove('has-overlay'); if(!rootElement.classList.length){ rootElement.removeAttribute('class'); } window.scrollTo({ top: scrollPosition, behavior: 'instant' }); if(element && element.getAttribute('aria-hidden') === 'false') { element.setAttribute('aria-hidden', true); } if (element && lastFocusedElement) { lastFocusedElement.focus(); } }