Search code examples
javascriptiphonehtmlfocusmobile-safari

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


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!


Solution

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