0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ぼくのJavaScript備忘録】addEventListener の使い方徹底解説

Last updated at Posted at 2025-02-04

1. addEventListener とは?

addEventListener は、JavaScript で イベントリスナーを設定 するためのメソッドです。
document や特定の要素を指定して、イベント(clickkeydown など)を監視し、特定の処理を実行できます。

document とは?
document は、ブラウザが読み込んだ HTML ドキュメント全体 を指すオブジェクトです。
ただし、document に直接イベントを設定するのではなく、特定の要素を変数に格納して扱うことも可能 です。


2. 基本的な使い方

document.addEventListener(イベント名, イベントハンドラ, オプション);

または、特定の要素を変数に格納してイベントリスナーを追加することもできます。

const button = document.getElementById("myButton");
button.addEventListener("click", () => {
    console.log("ボタンがクリックされました!");
});
  • イベント名:監視するイベント(例:clickkeydownscroll など)
  • イベントハンドラ:イベントが発生したときに実行される関数
  • オプション(省略可):イベントの詳細設定

3. 具体的な使用例

☑️ 例1:クリックイベントを監視

document.addEventListener("click", function() {
    console.log("ページがクリックされました!");
});

または、特定の要素のみに設定する場合:

const myButton = document.getElementById("myButton");
myButton.addEventListener("click", function() {
    console.log("ボタンがクリックされました!");
});

ページ全体 または 特定の要素 でクリックイベントを監視できる。


4. removeEventListener でイベントを削除

イベントリスナーを削除するには removeEventListener を使います。

☑️ 例2:クリックイベントを削除

function handleClick() {
    console.log("クリックされました!");
}

document.addEventListener("click", handleClick);
document.removeEventListener("click", handleClick);

または、変数に格納した要素に対して削除:

const myButton = document.getElementById("myButton");
function handleClick() {
    console.log("ボタンがクリックされました!");
}

myButton.addEventListener("click", handleClick);
myButton.removeEventListener("click", handleClick);

削除するには、関数を変数として渡す必要がある


5. useCapturepassive オプション

イベントリスナーには オプション を設定できます。

document.addEventListener("touchmove", function(event) {
    console.log("タッチイベント発生!");
}, { passive: true });

🔍 オプションの解説

オプション 説明
capture: true キャプチャフェーズ でイベントを処理(通常は false
passive: true スクロール最適化(イベント内で preventDefault() を使わない)
once: true 1回だけ実行 したらイベントリスナーを削除

6. どのようなイベント名があるか?

JavaScript のイベントの種類は多岐にわたります。
主要なイベントについては、Mozilla Developer Network (MDN)Element API のページで確認できます。

イベントの一覧はこちら


7. まとめ

☑️ document.addEventListener(イベント名, ハンドラ) でページ全体のイベントを追加できる
☑️ 特定の要素を変数に格納して addEventListener を適用できる
☑️ removeEventListener で不要なイベントを削除できる
☑️ passiveonce などのオプションを使うと最適化ができる
☑️ イベントの一覧は MDN の Element API を参照

このメソッドを活用すれば、インタラクティブな Web ページ を作れます!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?