Last active
April 29, 2024 18:12
-
-
Save pladaria/64e8c2bbd91b6ee121b4f2d7664eaf7e to your computer and use it in GitHub Desktop.
Detect if Virtual Keyboard is open in web app using React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const useIsVirtualKeyboardVisible = () => { | |
const [isVirtualKeyboardVisible, setIsVirtualKeyboardVisible] = React.useState(false); | |
React.useEffect(() => { | |
// probably incomplete, good enough for me | |
const inputTypesThatOpenTheVirtualKeyboard = ['text', 'email', 'password', 'number', 'search']; | |
const handleFocus = (event: Event) => { | |
if ( | |
event.target instanceof HTMLTextAreaElement || | |
(event.target instanceof HTMLInputElement && | |
inputTypesThatOpenTheVirtualKeyboard.includes(event.target.type)) | |
) { | |
setIsVirtualKeyboardVisible(true); | |
} | |
}; | |
const handleFocusOut = () => { | |
setIsVirtualKeyboardVisible(false); | |
}; | |
window.addEventListener('focusin', handleFocus, true); | |
window.addEventListener('focusout', handleFocusOut, true); | |
return () => { | |
window.removeEventListener('focusin', handleFocus, true); | |
window.removeEventListener('focusout', handleFocusOut, true); | |
}; | |
}, []); | |
return isVirtualKeyboardVisible; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment