LoginSignup
1
0

More than 1 year has passed since last update.

何かイベントが起きた時に指定の処理を実行させたい時
「addEventListener()」
というメソッドを使います。

構文

対象要素.addEventListener(イベントの種類,処理実行関数);

記述方法は上記構文のような、
「document」等の対象要素に対して
「addEventListener」を宣言して
第1引数に取得するイベントの種類(クリックした時、キーボードキーを押した時等)を指定して
第2引数に関数を指定して「第1引数イベント種類」が発生した時、関数内に書かれた処理を実行する
という意味になります。

例コード

document.addEventListener('keydown',function(event){
  console.log(event.key);
});

上記例コードは先ほどの構文にのっとり記述しています。
「document」に対して、
「addEventListener」を宣言し、
「keydown」で、「キーボードキーを押す」というイベントが発生した時に、
「function(event){console.log(event.key);}」で、押したキーの「キーコード」をコンソールに出力する
という意味になります。

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