Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

usagora

macrumors 601
Original poster
Nov 17, 2017
4,869
4,451
I have a vanilla Javascript web app that I've been developing for a while for personal use and this is the first time I've run into this issue with the .focus() method. When the app loads, you are given a choice to load data from local storage or from a backup. Since loading the backup overwrites local storage, I have an input field for a password to confirm (before I just had an ok and cancel button, but I want something even more intentional).

The issue is I can get the input field in focus on iOS (Safari, FireFox, or Chrome) when its parent div loads by using the .focus() method on the input's id, but for some reason the cursor does not move to the input field and therefore the onscreen keyboard does not come up. In those same browsers on macOS, it works fine (field is in focus AND cursor moves there). On iOS I know the field is in focus because I can see the *:focus CSS styling being applied to the field (changes from transparent border to a blue border). I even have a timeout set for the .focus() method (made it a whole second / 1000ms just to be sure), but the cursor still doesn't move there.

Here's my code (some irrelevant code has been removed for brevity):

HTML:
<div class="button" onclick="loadLatestBackup()">Latest Backup</div> <!--User clicks this button to load the latest backup data-->

JavaScript:
function loadLatestBackup() {
    pop(["wtlPop"],["pwdPop"]);
}

JavaScript:
function pop(closeArray,openArray) {
    for (let i = 0; i < closeArray.length; i++) {
        if (closeArray != []) {
            document.getElementById(closeArray[i]).style.display = "none";
        }
    }
    for (let i = 0; i < openArray.length; i++) {
        if (openArray != []) {
            document.getElementById(openArray[i]).style.display = "block";
        }  
    }
    if (openArray.includes("pwdPop")) {
        setTimeout(function() {
            document.getElementById("pwd").focus();
        },1000); // why isn't this working on iOS???
    }
    scrollTo(0,0);
}

HTML:
<div id="pwdPop" class="pop">
  <p>Enter password to confirm overwriting local storage:</p>
  <div>
    <input type="text" id="pwd" class="textInputField6" maxlength="4"> <!--this is the field I need both focus and cursor at-->
</div>

Here is a video contrasting the behavior on macOS (Safari) vs. iOS (Safari):
 
Last edited:

usagora

macrumors 601
Original poster
Nov 17, 2017
4,869
4,451
Well, I guess everyone here is stumped by it too, so I don't feel so bad now.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.