javascript イベント発生からイベントバブル(親要素までイベントが発生するか)を判定する
- 作成日 2021.09.20
- 更新日 2022.09.29
- javascript
- javascript
javascriptで、イベント発生からイベントバブル(親要素までイベントが発生するか)を判定するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 105.0.5195.127
イベント発生からイベントバブル(親要素までイベントが発生するか)を判定
イベント発生からイベントバブル(親要素までイベントが発生するか)を判定するには、「Event.bubbles」を使用します。
true イベントバブルである
false イベントバブルでない
<div id="oya">
<input id="ko" type="button" value="ボタン" />
</div>
<script>
'use strict'
function hoge(e){
console.log(`子要素が実行されました。 bubbles : ${e.bubbles}`)
}
function foo(e){
console.log(`親要素が実行されました。 bubbles : ${e.bubbles}`)
}
document.getElementById("ko").addEventListener('click', hoge, false)
document.getElementById("oya").addEventListener('click', foo, false)
</script>
実行結果を確認すると、ボタンをクリックすると、イベントバブルの状態が確認できます。
また、以下のコードを、
function hoge(e){
console.log(`子要素が実行されました。 bubbles : ${e.bubbles}`)
}
function foo(e){
console.log(`親要素が実行されました。 bubbles : ${e.bubbles}`)
}
document.getElementById("ko").addEventListener('click', hoge, false)
document.getElementById("oya").addEventListener('click', foo, false)
アロー関数とdocument.getElementByIdを省略して、簡潔に記述することもできます。
const hoge = (e) => {
console.log(`子要素が実行されました。 bubbles : ${e.bubbles}`)
}
const foo = (e) => {
console.log(`親要素が実行されました。 bubbles : ${e.bubbles}`)
}
ko.addEventListener('click', hoge, false)
oya.addEventListener('click', foo, false)
サンプルコード
以下は、
親子関係にある、各要素のクリックイベントでイベントバブルの状態を確認して表示するサンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>
<style>
</style>
<script>
window.onload = () => {
one.onclick = (e) => {
oya.textContent = `oya : ${e.bubbles}`
}
two.onclick = (e) => {
ko.textContent = `ko : ${e.bubbles}`
}
three.onclick = (e) => {
mago.textContent = `mago : ${e.bubbles}`
}
btn.onclick = (e) => {
oya.textContent = ''
ko.textContent = ''
mago.textContent = ''
}
}
</script>
<body>
<div class="container mx-auto my-56 w-1/3 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 id="oya" class="font-semibold text-gray-500 text-lg mr-auto"></h1>
<h1 id="ko" class="font-semibold text-gray-500 text-lg mr-auto"></h1>
<h1 id="mago" class="font-semibold text-gray-500 text-lg mr-auto"></h1>
<div id="one" class="bg-blue-500 rounded-full h-60 w-60 flex items-center justify-center">
<div id="two" class="bg-blue-300 rounded-full h-48 w-48 flex items-center justify-center">
<div id="three" class="bg-blue-100 rounded-full h-24 w-24 flex items-center justify-center">
</div>
</div>
</div>
<button id="btn"
class="w-1/6 bg-transparent hover:bg-pink-500 text-pink-700 font-semibold hover:text-white m-16 border border-pink-500 hover:border-transparent rounded">
reset
</button>
</div>
</div>
</body>
</html>
実行結果を確認すると、イベントバブルの状態が表示されていることが確認できます。
-
前の記事
node.js PostgreSQLにinsertを行う 2021.09.19
-
次の記事
Ruby ASCIIコードを文字列に変換する 2021.09.20
コメントを書く