Last active
October 11, 2019 14:11
-
-
Save n8jadams/8d63a97e00984e4b61a64a44ce651cca to your computer and use it in GitHub Desktop.
Focus And Open Keyboard. This is a nice cross-browser-compatible function that will focus on an input element and open the keyboard (on mobile devices). Especially useful for modals on IOS devices.
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
/* | |
// Example usage | |
var myElement = document.getElementById('my-element'); | |
var modalFadeInDuration = 300; | |
focusAndOpenKeyboard(myElement, modalFadeInDuration); // or without the second argument | |
*/ | |
function focusAndOpenKeyboard(el, timeout) { | |
if(!timeout) { | |
timeout = 100; | |
} | |
if(el) { | |
// Align temp input element approximately where the input element is | |
// so the cursor doesn't jump around | |
var __tempEl__ = document.createElement('input'); | |
__tempEl__.style.position = 'absolute'; | |
__tempEl__.style.top = (el.offsetTop + 7) + 'px'; | |
__tempEl__.style.left = el.offsetLeft + 'px'; | |
__tempEl__.style.height = 0; | |
__tempEl__.style.opacity = 0; | |
// Put this temp element as a child of the page <body> and focus on it | |
document.body.appendChild(__tempEl__); | |
__tempEl__.focus(); | |
// The keyboard is open. Now do a delayed focus on the target element | |
setTimeout(function() { | |
el.focus(); | |
el.click(); | |
// Remove the temp element | |
document.body.removeChild(__tempEl__); | |
}, timeout); | |
} | |
} | |
module.exports = focusAndOpenKeyboard; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment