viewport-height-fix
Version:
A utility to fix the mobile 100vh issue by setting a --vh CSS variable.
34 lines (33 loc) • 1.13 kB
JavaScript
let initialized = false;
function isBrowser() {
return typeof window !== 'undefined' && typeof document !== 'undefined';
}
function setVhVar() {
if (!isBrowser())
return;
requestAnimationFrame(() => {
const vh = window.innerHeight * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);
});
}
function debounce(fn, delay) {
let timeout = null;
return function (...args) {
if (timeout)
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), delay);
};
}
export function initViewportHeightFix() {
if (!isBrowser() || initialized)
return;
initialized = true;
const debouncedSetVhVar = debounce(setVhVar, 100);
setVhVar();
window.addEventListener('resize', debouncedSetVhVar);
window.addEventListener('orientationchange', debouncedSetVhVar);
window.addEventListener('focus', debouncedSetVhVar);
window.addEventListener('pageshow', debouncedSetVhVar);
document.addEventListener('visibilitychange', debouncedSetVhVar);
window.addEventListener('touchend', debouncedSetVhVar);
}