I can't find exact specifications on this, but it seems that iOS restricts bringing up the keyboard via programmatically focusing on <input>
. It only brings up the keyboard in response to explicit user interaction.
- iOS focus on input field only brings up keyboard when called inside a click handler.
- It doesn’t work if the focus is async.
This presents a curious problem when you want to autofocus an input inside a modal or lightbox, since what you generally do is click on a button to bring up the lightbox, and then focus on the input after the lightbox has been opened. Without anything fancy, it actually works ok. The problem shows up when you try to add something fancy like a setTimeout
or a promise.then()
. I don't know why people would want to use a setTimeout here, but waiting for a promise is actually a pretty common use case. E.g. we try to batch dom manipulations like getting a lightbox to show up inside requestAnimationFrame
. Also, it's possible that people would want to asynchronously wait for XHRs / data fetches. In any case, that use case is currently not supported by webkit / iOS.
- Vanilla onClick focus works: https://codepen.io/cathyxz/pen/XELrjO
- Promise with dom manipulation then focus works: https://codepen.io/cathyxz/pen/bMbypd
- Promise waiting for setTimeout then focus does NOT work: https://codepen.io/cathyxz/pen/odvRpm
- Promise with rAF then focus does NOT work: https://codepen.io/cathyxz/pen/QrLRvK
- setTimeout focus does NOT work: https://codepen.io/cathyxz/pen/debEog
- https://medium.com/@brunn/autofocus-in-ios-safari-458215514a5f
- vuejs/vue#7546
- https://stackoverflow.com/questions/12204571/mobile-safari-javascript-focus-method-on-inputfield-only-works-with-click
I spent a long time searching for this without success, so I'm documenting it here for anyone else that runs into the same issue.
For reference, we ran into this issue, which was hackily solved by this solution.
Maybe this problem: WebKit/WebKit#2907