LoginSignup
1
1

More than 3 years have passed since last update.

【Javascript】KeyboardEventを理解する

Last updated at Posted at 2019-06-29

今回も自分のメモ書き程度に。

keyupイベントで押したキーを離したときにjavascriptを実行する

keyupイベントは、押したキーが離れた時にjavascriptが実行されます。

いいサンプルがW3Schoolにあったので、掲載します。
This example uses the addEventListener() method to attach a "keyup" event to an input element.

<!DOCTYPE html>
<html>
<body>

<p>This example uses the addEventListener() method to attach a "keyup" event to an input element.</p>

<p>Press a key inside the text field and release it to set a red background color.</p>

Enter your name: <input type="text" id="fname">

<script>
document.getElementById("fname").addEventListener("keyup", myFunction);

function myFunction() {
  var x = document.getElementById("fname");
  x.value = x.value.toUpperCase();  //フォームに入力すると全部大文字になるように設定してある
}
</script>
</body>
</html>

(参考)keydownイベントとkeypressイベントもある

使い方は同じですが、keydownはキーを押した時、keypressはエンターキーを押した時にjavascriptが実行される。

1
1
1

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
1
1