読み書きプログラミング

日常のプログラミングで気づいたことを綴っています

ソフトウェアキーボードを出現させずにテキスト欄にフォーカスする方法

<body>
<input id="target" type="text" />
</body>
$('#target').on 'touchstart', (event) ->
    $this = $(this)
    event.preventDefault()
    setTimeout (->$this.trigger 'focus'), 200

簡潔のため、jQuery使ってCoffeeScriptで記述しました。
setTimeoutは200ms程度必要です。150ms程度だとキーボードが出現することがあります。

以下は動作する全コード。

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>Focus without onboard keyboard</title>
  <style type="text/css">
  input:focus {
    border: solid 2px red;
  }
  </style>
</head>
<body>
  <p>フォーカスすると枠が赤くなります。</p>
  <input id="target" type="text" />
  <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
  <script type="text/javascript">
  $('#target').on('touchstart', function(event) {
    var $this;
    $this = $(this);
    event.preventDefault();
    return setTimeout((function() {
      return $this.trigger('focus');
    }), 200);
  });
  </script>
</body>
</html>