Created
August 21, 2009 08:06
-
-
Save padolsey/171716 to your computer and use it in GitHub Desktop.
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
// Usage: | |
// Target all links with an ID starting with "notice" | |
delegateEvent({nodeName:/^a$/i, id: /^notice/}, 'click', function(){ | |
alert(this.id); | |
}); | |
function delegateEvent(props, type, handler) { | |
var fn = function(e) { | |
e = e || window.event; | |
var target = e.target || e.srcElement, | |
parent = target, | |
p, prop, matches = false; | |
do { | |
matches = false; | |
for (p in props) { | |
if (!props.hasOwnProperty || props.hasOwnProperty(p)) { | |
prop = props[p]; | |
matches = prop.test ? prop.test(parent[p]) : prop === parent[p]; | |
} | |
} | |
if (matches) { | |
return handler.call( parent, e ); | |
} | |
} while ( parent = parent.parentNode ); | |
return true; | |
}, | |
doc = document; | |
if (doc.addEventListener) { | |
doc.addEventListener( type, fn, false ); | |
} else { | |
if (doc.attachEvent) { | |
doc.attachEvent( 'on' + type, fn ); | |
} else { | |
var origHandler = doc['on' + type]; | |
doc['on' + type] = function(e) { | |
origHandler.call(this, e); | |
fn(e); | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment