Skip to content

Instantly share code, notes, and snippets.

@dannycallaghan
Created October 9, 2013 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dannycallaghan/6897868 to your computer and use it in GitHub Desktop.
Save dannycallaghan/6897868 to your computer and use it in GitHub Desktop.
Cross browser add and remove events - with init-time branching. From 'JavaScript Patterns' (O'Reilly) by Stoyan Stefanov.
/* Cross browser add and remove events - with init-time branching */
// the interface
var utils = {
addListener : null,
removeListener : null
};
// the implementation
if ( window.addEventListener ) {
utils.addListener = function ( el, type, fn ) {
el.addEventListener( type, fn, false );
};
utils.removeListener = function ( el, type, fn ) {
el.removeEventListener( type, fn, false );
};
} else if ( document.attachEvent ) { // IE
utils.addListener = function ( el, type, fn ) {
el.attachEvent( 'on' + type, fn );
};
utils.removeListener = function ( el, type, fn ) {
el.detachEvent( 'on' + type, fn );
};
} else { // older browsers
utils.addListener = function ( el, type, fn ) {
el[ 'on' + type ] = fn;
};
utils.removeListener = function ( el, type, fn ) {
el[ 'on' + type ] = null;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment