Created
April 20, 2016 11:10
-
-
Save HughDai/a365e2515643e861ceff6b6181400449 to your computer and use it in GitHub Desktop.
Cross browser event util
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 Utility | |
// Nicholas Zakas, Professional JavaScript for Web Developers p.441 | |
(function(window, document) { | |
'use strict'; | |
var | |
EventUtil = { | |
addHandler: function( element, type, handler ) { | |
if ( element.addEventListener ) { | |
element.addEventListener ( type, handler, false ); | |
} else if ( element.attachEvent ) { | |
element.attachEvent ( "on" + type, handler ); | |
} else { | |
element["on" + type] = handler; | |
} | |
}, | |
getEvent: function ( event ) { | |
return event ? event : window.event; | |
}, | |
getTarget: function ( event ) { | |
return event.target || event.srcElement; | |
}, | |
preventDefault: function ( event ) { | |
if ( event.preventDefault ) { | |
event.preventDefault(); | |
} else { | |
event.returnValue = false; | |
} | |
}, | |
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; | |
} | |
}, | |
stopPropagation: function ( event ) { | |
if ( event.stopPropagation ) { | |
event.stopPropagation(); | |
} else { | |
event.cancelBubble = true; | |
} | |
} | |
}; | |
var newAnchor = document.createElement( "a" ); | |
newAnchor.href = "#"; | |
newAnchor.appendChild ( document.createTextNode("Test Link") ); | |
document.body.appendChild(newAnchor); | |
newAnchor.onclick = function ( event ) { | |
var target; | |
event = EventUtil.getEvent ( event ); | |
EventUtil.preventDefault ( event ); | |
EventUtil.stopPropagation ( event ); | |
target = EventUtil.getTarget ( event ); | |
if ( "innerText" in target ) { | |
target.innerText = target.innerHTML + 'X'; | |
} else { | |
target.textContent = target.textContent + 'X'; | |
} | |
}; | |
})(window, window.document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment