HTML DOMドキュメントaddEventListener()
例
ドキュメントにクリックイベントを追加します。
document.addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
より単純な構文:
document.addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello World";
});
以下のその他の例。
定義と使用法
このaddEventListener()
メソッドは、イベントハンドラーをドキュメントに添付します。
構文
document.addEventListener(event, function, useCapture)
パラメーター
Parameter | Description |
event | Required. The event name. Do not use the "on" prefix. For example, use "click" instead of "onclick". HTML DOM events are listed in Complete HTML DOM Event Object Reference. |
function | Required. The function to run when the event occurs. When the event occurs, an event object is passed to the function as the first parameter. The type of the event object depends on the specified event. For example, the "click" event belongs to the MouseEvent object. |
useCapture |
Optional. A boolean. Specifies if the event should be executed in the capturing or in the bubbling phase (default). true - The event handler is executed in the capturing phase.false - The event handler is executed in the bubbling phase.
|
戻り値
NONE |
その他の例
ドキュメントに多くのイベントリスナーを追加できます。
document.addEventListener("click", myFunction1);
document.addEventListener("click", myFunction2);
さまざまなタイプのイベントを追加できます。
document.addEventListener("mouseover", myFunction);
document.addEventListener("click", someOtherFunction);
document.addEventListener("mouseout", someOtherFunction);
パラメータを渡すときは、「無名関数」を使用して、パラメータを使用して関数を呼び出します。
document.addEventListener("click", function() {
myFunction(p1, p2);
});
ドキュメントの背景色を変更します。
document.addEventListener("click", function(){
document.body.style.backgroundColor = "red";
});
removeEventListener()メソッドの使用:
// Add an event listener
document.addEventListener("mousemove", myFunction);
// Remove event listener
document.removeEventListener("mousemove", myFunction);
ブラウザのサポート
document.addEventListener
DOMレベル2(2001)の機能です。
すべてのブラウザで完全にサポートされています。
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |