Created
June 10, 2012 15:59
-
-
Save akikoo/2906364 to your computer and use it in GitHub Desktop.
Cross-browser event object
This file contains 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
/** | |
* Cross-browser event object | |
* Adapted from Professional JavaScript for Web Developers, 3rd Edition, by Nicholas C. Zakas | |
* | |
* Usage example: | |
* | |
* eventUtil.addHandler(elm, "click", function (e) { | |
* e = eventUtil.getEvent(e); // Get event object | |
* eventUtil.preventDefault(e); // Prevent default action | |
* }); | |
* | |
*/ | |
(function (window) { | |
'use strict'; | |
var eventUtil = { | |
addHandler: function (element, type, handler) { | |
if (element.addEventListener) { // W3C | |
element.addEventListener(type, handler, false); | |
} else if (element.attachEvent) { // IE | |
element.attachEvent("on" + type, handler); | |
} else { | |
element["on" + type] = handler; | |
} | |
}, | |
removeHandler: function (element, type, handler) { | |
if (element.removeEventListener) { | |
element.removeEventListener(type, handler, false); | |
} else if (element.detachEvent) { | |
element.detachEvent("on" + type, handler); | |
} else { | |
element["on" + type] = null; | |
} | |
}, | |
// Get event element | |
getEvent: function (e) { | |
return e || window.event; // Dom event object || IE event object | |
}, | |
// Get source element | |
getTarget: function (e) { | |
return e.target || e.srcElement; // Dom event object || IE event object | |
}, | |
// Prevent default action | |
preventDefault: function (e) { | |
if (e.preventDefault) { // Dom event object | |
e.preventDefault(); | |
} else { // IE event object | |
e.returnValue = false; | |
} | |
}, | |
// Cancel event bubbling | |
stopPropagation: function (e) { | |
if (e.stopPropagation) { // Dom event object | |
e.stopPropagation(); | |
} else { // IE event object | |
e.cancelBubble = true; | |
} | |
} | |
}; | |
}(window)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment