DOMイベントメモ
JavaScriptのイベントは、ユーザーの入力や操作に反応して処理を実行する仕組み です。
クリック・フォーム入力・キー操作などをトリガーにして、インタラクティブなUIを作れます。
インラインイベントハンドラー(非推奨)
HTMLに直接書く方法は おすすめできません。
(HTMLとJSが混ざるため保守が難しくなります)
<button onclick="alert('剣を装備した!')">装備する</button>
イベントハンドラー(プロパティ形式)
要素を取得して、プロパティとしてイベントを割り当てる方法。
const btn = document.querySelector('#equip');
btn.onclick = function () {
console.log('装備ボタンが押されました!');
};
addEventListener
複数のイベントを設定でき、実務でよく使われる方法です。
const btn3 = document.querySelector('#attack');
btn3.addEventListener('click', () => {
alert('ドラゴンに攻撃した!');
});
イベントと this
イベント内の this は「そのイベントが発火した要素」を指します。
これを利用してクリックされたボタンの見た目を変えることができます。
const makeRandomColor = () => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
};
const buttons = document.querySelectorAll('button');
for (let button of buttons) {
button.addEventListener('click', function () {
this.style.backgroundColor = makeRandomColor();
});
}
フォームイベントと preventDefault()
冒険者がギルドに「依頼」を投稿するフォームを例にします。
デフォルトではフォーム送信時にページがリロードされるので、
e.preventDefault() で止めて処理を書きます。
const questForm = document.querySelector('#questForm');
const questBoard = document.querySelector('#quests');
questForm.addEventListener('submit', function (e) {
e.preventDefault();
const heroName = questForm.elements.hero.value;
const quest = questForm.elements.quest.value;
const newQuest = document.createElement('li');
const bTag = document.createElement('b');
bTag.append(heroName);
newQuest.append(bTag);
newQuest.append(` が新しい依頼を投稿しました: 「${quest}」`);
questBoard.append(newQuest);
});
input と change イベント
-
change… 入力が確定したときに発火 -
input… 文字が入力されるたびに発火
const input = document.querySelector('input');
const h1 = document.querySelector('h1');
input.addEventListener('change', function () {
console.log('入力が確定しました!');
});
input.addEventListener('input', function () {
h1.innerText = `勇者の名前: ${input.value}`;
});
イベントのバブリング
子要素で発生したイベントが親要素に伝わる現象を バブリング と呼びます。
必要なら e.stopPropagation() で止めることができます。
document.querySelector('#sword').addEventListener('click', (e) => {
console.log('剣がクリックされた');
e.stopPropagation(); // 親に伝わらない
});
document.querySelector('#inventory').addEventListener('click', () => {
console.log('インベントリ全体がクリックされた');
});
イベントデリゲーション
アイテムが増えるリストに、ひとつずつイベントをつけるのは非効率。
そこで、親要素でイベントを受け取り、子要素を判別して処理する方法です。
const bag = document.querySelector('#bag');
bag.addEventListener('click', function (e) {
if (e.target.nodeName === 'LI') {
alert(`${e.target.innerText} を使った!`);
e.target.remove(); // 使用後アイテムを削除
}
});
まとめ
- イベントは ユーザー操作に応じて処理を走らせる仕組み
-
addEventListenerが基本 -
thisで対象要素に直接アクセスできる -
preventDefault()でフォームやリンクのデフォルト動作を制御可能 - バブリング と デリゲーション を理解すると効率的なコードが書ける