How to listen for keyboard open/close in Javascript/Sencha?

霸气de小男生 提交于 2019-11-30 12:41:54

Keyboard will be automatically invoked while you are focusing textfield, textareafield ... . So you can create listener to the focus event in javascript which is similar to listening to the keyboard open event. Also you can use the blur listener to handle the keyboard close.

Thanks.

I've encountered the same issue, and I think that the best solution in your case is to use a PhoneGap plugin which will bind the native events, like this one :

https://github.com/driftyco/ionic-plugins-keyboard/tree/60b803617af49a10aff831099db90340e5bb654c

It works great on Android and iOS the same way, just bind those events:

window.addEventListener('native.showkeyboard', keyboardShowHandler);

window.addEventListener('native.hidekeyboard', keyboardHideHandler);

Triggering open status is easy using onclick or onfocus event, but on closing keyboard onblur event is not fired (because cursor remains in input/textarea). So I found solution by detecting window height which is significantly changed on keyboard open/close.

It is working in modern browsers on Android and iOS too. Demo: http://jsfiddle.net/qu1ssabq/3/

If necessary you can improve my code for devices which do not support addEventListener or innerHeight - there are available alternatives on the Internet.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0, minimal-ui">
<title>Detect keyboard opened/closed event</title>
</head>
<body>

<textarea id="txta" onclick="xfocus()" onblur="xblur()"></textarea><br>

<span id="status" style="background: yellow; width: auto;">closed</span>

<script type="text/javascript">
  function xfocus() {
    setTimeout(function() {
      height_old = window.innerHeight;
      window.addEventListener('resize', xresize);
      document.getElementById('status').innerHTML = 'opened'; // do something instead this
    }, 500);
  }
  function xresize() {
    height_new = window.innerHeight;
    var diff = Math.abs(height_old - height_new);
    var perc = Math.round((diff / height_old) * 100);
    if (perc > 50)
      xblur();
  }
  function xblur() {
    window.removeEventListener('resize', xresize);
    document.getElementById('status').innerHTML = 'closed'; // do something instead this
  }
</script>

</body>
</html>

As far as I can see this is only possible in the Android builds for PhoneGap, see the pull request here: https://github.com/phonegap/phonegap-android/issues/94.

The events are called hidekeyboard and showkeyboard. You might check whether they fire on iOS too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!