How to force close ipad/iphone keypad when input element is not focused using JS?

1.2k views Asked by At

I have an input field inside iframe, so when I click any input field, it gets focused. But again if I click outside (body area), the iphone keypad is not closed. Whenever I click done button explicity, it closed. Problem with only iphone and ipad inside iframes. This will work nicely in all browsers. So, I tried if there is no focus, called blur() or document.activeelement. but none of them are working.

Tried this, focus is triggered but focusout is not triggered.

document.addEventListener("focusout", function(){
      document.activeElement.blur();
  });

Any fix for this?

sample.html

<!doctype html>
<html>
<head>
</head>
<body>
<iframe src="index2.html" width="100%" height="200px"></iframe>
</body>
</html>

index2.html

<!doctype html>
<html>
<head>
<style>
input:focus{
border: 2px solid red;
}
</style>
</head>
<body>
<br></br>
<input type="text" id="myText"/>
</body>
</html>
1

There are 1 answers

4
Reming Hsu On

I don't know why blur() not work inside iframe, but it does work without iframe.

So I did a couple of tests, and finally I found them:

  1. alert() Simple alert something, it will close keypad.
  2. focus() on a non text element, like the button.

Here i show how do i do it used focus():

sample.html

<!doctype html>
<html>
<head>
</head>
<body>
<iframe src="index2.html" width="100%" height="200px"></iframe>
</body>
</html>
<script>
    document.getElementById("myframe").addEventListener("load",function()
        {
            document.getElementById("myframe").contentWindow.document.addEventListener("touchend",touchEnd, false);
        }, false
    );

    document.addEventListener("touchend",touchEnd, false);

    function touchEnd(event) {
       if(event.changedTouches[0].target.id != "mytext")
       {
            document.getElementById("myframe").contentWindow.document.getElementById("hidekeyboard").focus();
       }
    }
</script>

index2.html

<!doctype html>
<html>
<head>
<style>
input:focus{
border: 2px solid red;
}
</style>
</head>
<body>
<br></br>
<input type="text" id="myText"/>
<button type="button" id="hidekeyboard" style="width:0px; height:0px; opacity:0;"></button>
</body>
</html>