15

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!

Tuna
  • 2,937
  • 4
  • 37
  • 61
pixelphantom
  • 531
  • 1
  • 5
  • 16

4 Answers4

17

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

Veera
  • 32,532
  • 36
  • 98
  • 137
1

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

Pulkit Aggarwal
  • 2,554
  • 4
  • 23
  • 33
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>
Maverick
  • 1,988
  • 5
  • 24
  • 31
  • 1
    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 =/ – pixelphantom Apr 24 '11 at 17:06
  • No idea why, it should work, check this article for more options => http://diveintohtml5.org/forms.html you will find what you need under Autofocus Fields – Maverick Apr 24 '11 at 17:24
  • @Husar it's not supported in mobile safari -- http://wufoo.com/html5/attributes/02-autofocus.html – Connor Aug 05 '12 at 22:43
-2

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

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

I hope, it would be working on all.

Leopathu
  • 624
  • 6
  • 11
  • That won't work, specially when you're using `timeout`. Could work in some cases, but only if you're not using timeout. – Sayed Mar 02 '17 at 10:54