サンプル集  >  HTML  >  イベントリスナー
イベントリスナー
2026/01/27

イベントリスナーを使ってみます。

◆環境
OS Windows 11 Home 25H2
Browser Google Chrome 143.0.7499.193

index.htmlではscriptタグでmain.jsを指定します。 イベントリスナーで使うbuttonタグを追記しました。

index.html
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
<!doctype html>
<head>
<meta charset="utf-8">
<title>イベントリスナー</title>
</head>
<body>
  <script type="module" src="main.js"></script>
  <button>ボタン</button>
</body>
</html>

main.jsではquerySelectorでbuttonのDOMを取得しaddEventListnerでfn関数を指定します。

main.js
1: 
2: 
3: 
4: 
5: 
6: 
7: 
function fn(e) {
    console.log('Hello!!');
    console.log(e);
}

const btn = document.querySelector('button');
btn.addEventListener('click', fn)

index.htmlを右クリックしOpen with Live Serverをクリック後、開いたブラウザでF12でDeveloper toolsを開きボタンをクリックしたところDeveloper toolsのConsoleにHello!!と表示されました!


期待通りに動作しました。

▲ PageTop  ■ Home


Copyright (C) 2026 ymlib.com