Search code examples
javascriptandroidhtmlkik

Why must the user tap inside my app before events (like Focus etc) work?


I've been messing around in a Kik web app for Android. I noticed that certain events do not fire properly until the user has interacted with the page.

The problem manifests itself in Kik, but it also shows up in the stock web browser on my Galaxy S5 running Android 4.4/KitKat.

HTML

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>  
click here: <button id="button">a button</button>
<br><br><br>
textbox: <input type="text" id="textbox">

CSS

* {
    font-size: 20px;
}

JavaScript

window.onload=function(e) {
    // set function to button.click
    $('#button').click(function() {
        fucus();
    });

    // run the exact same function rightey-right now
    $('#textbox').focus();

    // run it again in three minutes
    $('#textbox').focus()
};


function fucus() {
    $('#textbox').focus();
}

Solution

  • Most mobile browsers do not allow .focus() to behave as expected unless called from a user-interaction event. For example if you called it in an onclick event it would work but if called in onload it will not. This is not specific to Kik but rather mobile browsers in general.