Created
April 18, 2012 13:59
-
-
Save s-hiroshi/2413756 to your computer and use it in GitHub Desktop.
JavaScript > pattern > cross browser event listener (JavaScriptパターン p194)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<p><button id="foo">Click</button></p> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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