Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically focus on a textfield on page load for mobile safari?

Note: Due to a work-related change, I can no longer verify the answers posted here. Most likely, I will never be able to accept an answer down below. The information posted here is useful IMO, so I will just leave it as it is. If you think you know an answer, feel free to answer and we'll just let the community decide which ones are useful.


Background

I am developing a standalone web app for iPod Touch. One of my requirements is to focus on a textfield when a page loads so that a user can do a task continually (e.g. with a barcode reader).

Problem

The problem is that it does focus on the text field in question, but the keyboard does not go up. Is there a workaround for this? Or is this by design by Apple?

Sample Html

I'm unsure on how to put this into a code snippet, but this is where I've been experimenting on:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0.0">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <link rel="apple-touch-icon" href="https://cdn57.androidauthority.net/wp-content/uploads/2016/06/android-win-2-300x162.png">

    <title>TESTING</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <script>
        // javascript goes here
    </script>
</head>
<body>

    <section id="content">

        <div class="container" style="margin-top: 50px;" >

            <p>Testing textfield focus</p>

            <form method="POST">
                <div class="row">
                    <div class="col-xs-12">
                        <input type="text" class="form-control first-responder" />
                    </div>
                    <div class="col-xs-12">
                        <button type="submit" class="btn" style="width: 100%" >OK</button>
                    </div>
                </div>
            </form>

        </div>

    </section>

</body>
</html>

I view this on Safari, then add it to the homescreen so that it would act as a standalone web app.

Attempts

I tried searching around for solutions, the first one(I lost the link) suggested to try timeouts like so:

$(function () {
    var firstResponder = $(".first-responder");
    setTimeout(function() {
        firstResponder.focus();

    }, 1000);

})

Another of the solutions I found suggested to set the selection range like so:

$(function () {
    var firstResponder = $(".first-responder");
    setTimeout(function() {
        firstResponder[0].setSelectionRange(0, 9999);

    }, 1000);

})

There was also a suggestion to bind it to a click like so:

$(function () {
    var firstResponder = $(".first-responder");
    firstResponder.on('click', function() {
        firstResponder.focus();
    });

    firstResponder.focus().click();
})

I also tried triggering a touchstart like so:

$(function () {
    var firstResponder = $(".first-responder");
    firstResponder.on('touchstart', function() {
        firstResponder.focus();
    });

    firstResponder.trigger('touchstart');
})

I also tried with a simple ajax call like so (don't mind the success/error. All I wanted to do was focus after ajax call):

function doAjax() {
    var firstResponder = $(".first-responder");

    $.ajax({
        url: "#",
        method: "POST",
        dataType: "json",
        success: function(result) {
            firstResponder.focus();
        },
        error: function(request, error) {
            firstResponder.focus();         
        }
    });
}

I got kind of desperate so I tried setting some css too:

user-select: text;
-webkit-user-select: text;

These solutions worked on iOS 9.1 (except the css one) but all of them failed on iOS 11.1.1. I tried combining various solutions, setting timeouts, etc. but none seem to work. As I noted, it does focus because I can see that the textfield's borders turn blue, signifying that it has focus. But I need to have the keyboard displayed too.

This behavior seems to be either a bug or a usability/security feature. If this is by design (i.e. a security feature), is there an official documentation by Apple that talks about this?

Addendum

If you think that the barcode reader might be the problem, this is not true. In the project I'm working on, the barcode reader replaces the native keyboard. In theory, even without the barcode, as long as I am able to bring up the keyboard on page load, I should be able to fulfill my requirement.

Continuous task is possible because the barcode reader can include an Enter key after the barcode it reads, thereby submitting the form the textfield is on. After the page reloads, if the textfield gets automatically focused, all the user needs to do is read another barcode. The page submits again, reloads, autofocuses, and the cycle can be repeated.

like image 529
Keale Avatar asked Jan 12 '18 10:01

Keale


3 Answers

After some hard on tests I found a way that worked in my girlfriend's iphone 7 with ios 11, now I don't know if it gets to your needs, but it does pop the virtual keyboard!

This is the test html:

<input type='text' id='foo' onclick="this.focus();">
<button id="button">Click here</button>

This is the javascript:

function popKeyboard(input) {
  input.focus();
  input.setSelectionRange(0, 0);
}

$("#button").on("click", function() {
  popKeyboard($("#foo"));
});

And this is the fiddle.

Oh and CanIUse just in case!

Now what this does is when we click the button, this evaluates as User Input, because the keyboard can only be popped up if the user gives input ( in android and ios ), we run the function popKeyboard, which focus the input and sets the selectionRange to 0,0 which means it sets the caret to 0 and the keyboard should pop up.

This was tested in Android and an Iphone 7 with IOS 11.

Be wary that she did warned me that her ios 11 wasn't fully updated, but if it works please do tell me!

like image 111
Ivo Silva Avatar answered Sep 23 '22 14:09

Ivo Silva


Have you try this?

 $(function(){
    $('input.form-control.first-responder').first().focus();
  });

The selector gets narrowed down by first() and ensures that it not affected by other similar classes in the page.

like image 26
s1mpl3 Avatar answered Sep 22 '22 14:09

s1mpl3


Have a look at this question w/ solution: jQuery Set Cursor Position in Text Area

If you use the functions described in this solution right after the ajax ready event the keyboard will show up even in Safari on iOS 11.2.2

like image 30
Florian Chrometz Avatar answered Sep 23 '22 14:09

Florian Chrometz