Skip to content

Instantly share code, notes, and snippets.

@s-hiroshi
Created April 18, 2012 13:59
Show Gist options
  • Save s-hiroshi/2413756 to your computer and use it in GitHub Desktop.
Save s-hiroshi/2413756 to your computer and use it in GitHub Desktop.
JavaScript > pattern > cross browser event listener (JavaScriptパターン p194)
<html>
<body>
<p><button id="foo">Click</button></p>
</body>
</html>
var utils = {
addListener: null,
removeListener: null
};
if (typeof window.addEventListener === 'function') {
utils.addListener = function(elem, type, fn) {
elem.addEventListener(type, fn, false);
};
utils.removeListener = function(elem, type, fn) {
elem.removeElementListener(type, fn, false);
};
} else if (typeof document.attachEvent === 'function') {
utils.addListener = function(elem, type, fn) {
elem.addEvent('on' + type, fn);
};
utils.removeListener = function(elem, type, fn) {
elem.deleteListener('on' + type, fn);
};
} else { // 最終手段
utils.addListener = function(elem, type, fn) {
elem['on' + type] = fn;
};
utils.removeListener = function(elem, type, fn) {
elem['on' + type] = null;
};
}
// 実行例
var elem = document.getElementById('foo');
utils.addListener(elem, 'click', function () {
alert('foo');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment