Reputation: 617
I want to focus the first field in my HTML form on page load and I'm currently doing this using <input autofocus='autofocus' />
.
When I view the page on mobile, the soft keyboard covers the submit button, which isn't in-line with the designs I'm following. How do I get this keyboard to stay hidden until the user taps the field again?
I'd like the field to be focused on page-load so that desktop users can start typing into the field straight away. Mobile users would only need to tap the field once to bring up the soft keyboard.
We're not using any kind of user agent sniffing and we're not using viewport width to determine which browsers will have a soft keyboard.
Here's an example of what I'm looking to do. On a mobile device, the top field is focused but no keyboard is shown on mobile: https://accounts.ft.com/login
Upvotes: 4
Views: 2847
Reputation: 3424
That can be achieved by making the input field readonly
, then setting a timeout to blur
and then re-focus
on it, as well removing the readonly
attribute.
el = document.getElementById('myInput');
hideKeyboard(el);
function hideKeyboard(el) {
var att = document.createAttribute("readonly");
el.setAttributeNode(att); // Force keyboard to hide on input field.
setTimeout(function() {
el.blur(); //close the keyboard
el.focus(); //focus on the input
// Remove readonly attribute after keyboard is hidden.
el.removeAttribute('readonly');
}, 100);
}
<input id='myInput' autofocus />
Upvotes: 5