7.1 Event Bubbling (イベントのバブリング)
JavaScriptでは、ある要素で発生したイベントがDOMツリーを通じて伝播することがあります。このプロセスは イベント伝播と呼ばれ、主に2つのメカニズムを含みます:イベントのバブリング (event bubbling) と イベントキャプチャリング (event capturing)。
イベント伝播のメカニズム:
- Event Bubbling (イベントのバブリング)。
- Event Capturing (イベントキャプチャリング)。
イベントのバブリングとは、子要素で発生したイベントが順番に親要素を通じて ルート要素(通常はdocument
)まで上向きに伝播するプロセスです。
説明:
- ボタン
child
が押されたとき、まずイベントハンドラーがchild
要素で発火します(Child clicked
) - その後、イベントは
parent
要素にバブリングし、そのハンドラーが発火します(Parent clicked
)
例:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Event Bubbling Example</title>
</head>
<body>
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
const parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.addEventListener('click', function(event) {
console.log('Parent clicked');
});
child.addEventListener('click', function(event) {
console.log('Child clicked');
});
</script>
</body>
</html>
7.2 Event Capturing (イベントキャプチャリング)
イベントキャプチャリングとは、イベントがまずルート要素からターゲット要素まで親要素を通じて下向きに伝播するプロセスです。
イベントキャプチャリングを使用するには、イベントハンドラーを追加する際にcapture
パラメータをtrue
に設定する必要があります。
説明:
- ボタン
child
が押されたとき、まず親要素のイベントハンドラーがcapture
パラメータをtrue
に設定したために発火します (Parent clicked
) - 次にイベントがターゲット要素
child
に達し、そのハンドラーが発火します(Child clicked
)
例:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Event Capturing Example</title>
</head>
<body>
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
const parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.addEventListener('click', function(event) {
console.log('Parent clicked');
}, true);
child.addEventListener('click', function(event) {
console.log('Child clicked');
});
</script>
</body>
</html>
7.3 3フェーズのイベント伝播モデル
DOMにおけるイベント処理の過程には3つのフェーズがあります:
1. Capturing Phase (キャプチャフェーズ)。イベントはルート要素(通常はdocument)からターゲット要素まで親要素を通じて伝播します。
2. Target Phase (ターゲットフェーズ)。イベントは発生したターゲット要素に達します。
3. Bubbling Phase (バブリングフェーズ)。イベントはターゲット要素からルート要素まで親要素を通じて伝播します。
イベント伝播の制御
イベント伝播を管理するためのメソッドがあります:
stopPropagation()
。バブリング中またはキャプチャリング中のイベントのさらなる伝播を停止します。stopImmediatePropagation()
。イベントのさらなる伝播を停止し、現在の要素の他のイベントハンドラーの実行を防ぎます。preventDefault()
。イベントに関連付けられたデフォルトアクション(例:ボタンをクリックしてフォームを送信すること)をキャンセルします。
7.4 stopPropagationの使用例
説明:
- ボタン
child
が押されたとき、child
要素のイベントハンドラーが発火します(Child clicked
) event.stopPropagation()
を使用してイベントのバブリングが停止され、parent
要素のイベントハンドラーは発火しません
HTML
<!DOCTYPE html>
<html>
<head>
<title>Stop Propagation Example</title>
</head>
<body>
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
const parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.addEventListener('click', function(event) {
console.log('Parent clicked');
});
child.addEventListener('click', function(event) {
console.log('Child clicked');
event.stopPropagation(); // イベントのバブリングを停止
});
</script>
</body>
</html>
GO TO FULL VERSION