javascript 発生したイベントの種類を取得する
- 2020.09.26
- javascript
- javascript

javascriptで、 event.typeを使用して、発生したイベントの種類を取得するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ firefox 80.0.1
event.type使い方
event.typeを使えば、発生したイベントの種類を取得することが可能です。
1 2 3 4 5 6 7 8 9 10 11 |
/* html */ <button onclick="hoge();" id="btn"> 実行 </button> /* js */ function hoge() { var type = event.type; // id取得 console.log(type); // click } |
サンプルコード
以下は、
クリックイベントを登録した「実行」ボタンをクリックとテキストフォームにキーダウンすると、イベントの種類を取得して表示する
サンプルコードとなります。
※cssには「bootstrap material」を使用してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" id="css"> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 30px; } </style> <script> function hoge() { // イベントのタイプを取得 var type = event.type; // イベントのタイプを取得して表示 document.getElementsByClassName('badge')[0].textContent = type; } window.onload = function () { // ボタンを取得 var elmbtn = document.getElementById('btn'); // クリックイベントを登録 elmbtn.onclick = function () { hoge(); }; // ボタンを取得 var elmtxt = document.getElementById('txt'); // クリックイベントを登録 elmtxt.onkeydown = function () { hoge(); }; } </script> <body> <div class="main"> <h2><span class="badge badge-success">イベントの種類を取得</span></h2> <button id="btn" type="button" class="btn btn-raised btn-danger"> 実行 </button> <div class="form-group"> <input type="text" class="form-control" id="txt"> </div> </div> </body> </html> |
イベントの種類が取得されていることが確認できます。

-
前の記事
javascript 桁数を揃えるため数字の先頭に0を付ける 2020.09.26
-
次の記事
javascript グリニッジ標準時を取得する 2020.09.26
コメントを書く