LoginSignup
9
10

More than 5 years have passed since last update.

HTMLテキストフィールド入力値に対する日本語 IME のハンドリング

Posted at

よくある「テキスト入力によるフィルタリング」みたいな機能の際に、日本語 IME による入力が未確定の場合はイベントを発火したくないというのをうまくやるやつ。

<html>
  <head></head>
  <body>
    <input id="foo" type="text" value="" />
    <script>
      var onComposition = false;
      var input = document.getElementById("foo");

      input.addEventListener('keyup', function (e) {
          if (onComposition) return;
          console.log(e.target.value);
      });
      input.addEventListener('compositionstart', function () {
          onComposition = true;
      });
      input.addEventListener('compositionend', function () {
          onComposition = false;
      });
    </script>
  </body>
</html>

参考

IME handling guide
https://developer.mozilla.org/en-US/docs/Mozilla/IME_handling_guide

9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10