Skip to content

Instantly share code, notes, and snippets.

@padolsey
Created August 21, 2009 08:06
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 padolsey/171716 to your computer and use it in GitHub Desktop.
Save padolsey/171716 to your computer and use it in GitHub Desktop.
// 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