Oct 6, 2012

Phonegap + iScroll: solving keyboard issues

First of all, i must say that I'm using iScroll 4.2 with Phonegap 2.1 on an android project (eclipse), but this hack should work with other platforms and versions.

If you tried to click an input field (text box, select, etc) when using iScroll and phonegap, you will find out that you can't. That's because iScroll prevents the default behaviour of your click, making impossible to enter text or select anything.

I found the fix for this at Stack Overflow, however a new problem appears: the keyboard doesn't hide by itself when you put text inside the box!

To fix this, i hacked a bit the code from Stack Overflow. The final result is like this:

Step 1: change this code on iscroll.js :

    onBeforeScrollStart: function (e) { e.preventDefault(); },

and put this:

            onBeforeScrollStart: function (e) {
                var nodeType = e.explicitOriginalTarget ? e.explicitOriginalTarget.nodeName.toLowerCase():(e.target ? e.target.nodeName.toLowerCase():'');
               
                if(nodeType !='select' && nodeType !='option' && nodeType !='input' && nodeType!='textarea' && !showkey) {
                     e.preventDefault();    //prevents showing keyboard - scrolling
                }//otherwise, show keyboard, do default
                if(!showkey) showkey = true;
            },           

Then you must declare the variable "showkey" at the beginning of iscroll.js:

var showkey =true;

Then on your "onblur" events of your inputs you must put:

    <input onblur="showkey=false" .../>

So when you make onblur, the "e.preventDefault()" code can't be executed just one time, making default behaviour (hiding keyboard) possible.

2 comments:

  1. This helped me A LOT, I wasn't even aware that this problem was caused by iScroll, I guess one should approach html5 mobile development as a controlled experiment and check everything after introducing a new element, I thought it was an Android bug all along.
    I love you and thanks.

    ReplyDelete
    Replies
    1. I'm glad I could help you :-) In fact I guess iScroll was not designed with Android in mind, so some weird interactions like this may happen. Fortunately it's code is not very hard to understand :-)

      Delete