How can you autofocus on a form field in iPhone Safari?
Asked Answered
R

4

16

I'm trying to have a particular form field get focus automatically in a Safari browser on iPhone. I thought this would be pretty straight-forward, but I'm not managing to get this working. So, is this actually not possible or am I missing something super-obvious (which I suspect)? Here is the code I'm using:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
   function formfocus() {
      document.getElementById('element').focus();
   }
   window.onload = formfocus;
</script>
</head>
<body>

<form>
<input/>
<input id="element" autofocus/>
<input/>
</form>

</body>
</html>

You can see I'm trying to get the focus twice, once via js and once via the HTML "aufofocus" attribute on the input field. Neither does the trick. This does work on desktop browsers, but when I open the page on my iPhone 4, no dice, that is, I have to set focus manually by clicking on one of the form fields.

Ultimately what I'd like is to open the website on the mobile browser and have focus on a form field, including the keyboard opened up to start typing.

Thanks for any help!

Rephrase answered 24/4, 2011 at 16:35 Comment(0)
B
17

According to this page, autofocus is not supported in iphone/ipad for usability reasons.

Begrudge answered 15/9, 2011 at 17:53 Comment(0)
M
2

According to apple autoocus is not supported in iphone. There was a comment about it in a ticket for WebKit. The comment was created in March 2019, and states the following:

"We (Apple) like the current behavior and do not want programmatic focus to bring up the keyboard when [...] the programmatic focus was not invoked in response to a user gesture."

Source

Millhon answered 20/10, 2022 at 9:41 Comment(0)
A
0

Try to give the input element a type

<input type="email" id="element" autofocus/>

and for fallback you can use

<script type="text/javascript">
    if (!("autofocus" in document.createElement("input"))) {
      document.getElementById("element").focus();
    }
</script>
Armington answered 24/4, 2011 at 16:41 Comment(3)
Thanks Husar for that, I've updated the code accordingly (at the URL from above) but unfortunately it still doesn't work on on iPhone 4 =/Rephrase
No idea why, it should work, check this article for more options => diveintohtml5.org/forms.html you will find what you need under Autofocus FieldsArmington
@Husar it's not supported in mobile safari -- wufoo.com/html5/attributes/02-autofocus.htmlClutter
A
-2

Try the .focus() inside of setTimeout().

setTimeout(function() {
jQuery('#element').focus();
}, 500);

I hope, it would be working on all.

Aperture answered 6/2, 2015 at 7:5 Comment(1)
That won't work, specially when you're using timeout. Could work in some cases, but only if you're not using timeout.Armalda

© 2022 - 2024 — McMap. All rights reserved.