Skip to content

Instantly share code, notes, and snippets.

@greggnakamura
Created February 1, 2015 20:44
Show Gist options
  • Save greggnakamura/d33f0012f3a1124ebe5f to your computer and use it in GitHub Desktop.
Save greggnakamura/d33f0012f3a1124ebe5f to your computer and use it in GitHub Desktop.
Javascript: Feature Detection, Cross-Browser Event Handling example
// eventUtility.js
var eventUtility = {
addEvent: function (el, type, fn) {
/*
el: HTML element object (DOM object)
type: event type to listen to
fn: function
*/
// feature detection browser support
// can check for 'window' or 'document'
// First: test for standards compliance; check if 'addEventListener' is available
if (typeof addEventListener !== 'undefined') {
el.addEventListener(type, fn, false); // 'false'; specify capturing or bubbling (IE legacy)
}
// legacy; add 'on' to event type
else if (typeof attachEvent !== 'undefined') {
el.attachEvent('on' + type, fn); // capture or bubble check not necessary since bubbling is only option
}
// If does not support either, then assume DOM level 0
else {
el['on' + type] = fn;
}
},
removeEvent: function () {
if (typeof removeEventListener !== 'undefined') {
el.removeEventListener(type, fn, false);
}
else if (typeof detachEvent !== 'undefined') {
el.detachEvent('on' + type, fn);
}
else {
el['on' + type] = null;
}
},
getTarget: function () {
if (typeof event.target !== 'undefined') {
return event.target;
}
else {
return event.srcElement;
}
},
preventDefault: function () {
if (typeof event.preventDefault !== 'undefined') {
event.preventDefault();
}
else {
event.returnValue = false;
}
}
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style>
.normal { background-color: #fff; color: #000; }
.changed { background-color: #000; color: #fff; }
</style>
</head>
<body>
<button>Normal</button>
<button>Changed</button>
<script src="eventUtility.js"></script>
<script src="script.js"></script>
</body>
</html>
// script.js
(function () {
var buttons = document.getElementByTagName('button');
// change className based on button clicked
var buttonClick = function (e) {
var target = eventUtility.getTarget(e),
className = target.innerHTML.toLowerCase();
eventUtility.preventDefault();
document.body.className = className;
};
// for each element, call buttonClick function
for (var i = 0; len = buttons.length; i < len; i = i + 1) {
eventUtility.addEvent(buttons[i], 'click', buttonClick);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment