■概要
タグのon属性ではイベントに一つの関数のみ定義できましたが、EventListenerを使うと複数のイベントを登録することができます。
■使用方法
var testBtn = document.getElementById(“test-btn”);
// クリックイベント
testBtn.addEventListener(“click”, function (e) {
alert(“テストボタンが押されました”);
});function testMouseOverHandler(e) {
alert(“テストボタンの上にカーソルがあります”);
testBtn.removeEventListener(“mouseover”, testMouseOverHandler); // イベントの削除
}// マウスカーソルのイベント登録
testBtn.addEventListener(“mouseover”, testMouseOverHandler);
■Internet Explorer例外処理
addEventListenerなどの関数はIE9以上から使えます。
IE8はattachEvent関数があり、IE8以下のバージョンはonclickなどの属性を使います。
function addEventListenerOlder(obj1, event1, fun1) {
if (‘addEventListenerOlder’ in window) {
obj1.addEventListenerOlder(event1, fun1, false);
} else if (‘attachEvent’ in window) {
obj1.attachEvent(‘on’ + event1, fun1);
} else {
obj1[“on” + event1] = fun1;
}
}
上記のようなコードでも動作はしますが、jQueryを使った方が安全です。