pixelphantom
pixelphantom

Reputation: 551

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!

Upvotes: 16

Views: 30543

Answers (4)

Pulkit Aggarwal
Pulkit Aggarwal

Reputation: 2672

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

Upvotes: 2

Leopathu
Leopathu

Reputation: 624

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

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

I hope, it would be working on all.

Upvotes: -2

Veera
Veera

Reputation: 33202

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

Upvotes: 17

Maverick
Maverick

Reputation: 2016

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>

Upvotes: 0

Related Questions