Skip to content

Instantly share code, notes, and snippets.

@cododel
Last active July 18, 2025 16:51
Show Gist options
  • Save cododel/ecb141c4dd699af28a747b056d902a4a to your computer and use it in GitHub Desktop.
Save cododel/ecb141c4dd699af28a747b056d902a4a to your computer and use it in GitHub Desktop.
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no interactive-widget=resizes-content"/>
document.addEventListener("DOMContentLoaded", () => {
if (isSafari() && window.visualViewport) {
let { getValue: getOffsetTop, setValue: setOffsetTop } = useThrottledValue(
window.visualViewport.offsetTop,
100,
);
let keyboardIsOpen = false;
const hideKeyboardOnScrollWindow = (e) => {
const windowIsScrolled =
window.visualViewport.offsetTop !== getOffsetTop();
if (keyboardIsOpen && windowIsScrolled) {
document.activeElement.blur();
}
};
window.visualViewport.addEventListener("resize", (e) => {
const isInputFocused = ["INPUT", "TEXTAREA"].includes(
document.activeElement?.tagName,
);
if (isInputFocused && !keyboardIsOpen) {
keyboardIsOpen = true;
window.addEventListener("touchmove", hideKeyboardOnScrollWindow);
window.addEventListener("scroll", hideKeyboardOnScrollWindow);
}
if (!isInputFocused) {
keyboardIsOpen = false;
window.removeEventListener("touchmove", hideKeyboardOnScrollWindow);
window.removeEventListener("scroll", hideKeyboardOnScrollWindow);
}
setOffsetTop(window.visualViewport.offsetTop);
});
}
function isSafari() {
const userAgent = navigator.userAgent;
return userAgent.includes("Safari") && !userAgent.includes("Chrome");
}
function useThrottledValue(initialValue, delay) {
let rawValue = initialValue;
let throttledValue = initialValue;
let timeoutId = null;
const updateThrottledValue = () => {
throttledValue = rawValue;
};
return {
setValue: function (newValue) {
rawValue = newValue;
if (!timeoutId) {
updateThrottledValue();
timeoutId = setTimeout(() => {
timeoutId = null;
}, delay);
}
},
getValue: function () {
return throttledValue;
},
};
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment