Created
January 18, 2012 21:39
-
-
Save JeffreyWay/1635889 to your computer and use it in GitHub Desktop.
Legacy JS
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
// THE GOAL | |
// Write $('ul').on('click', 'a', fn); in JavaScript | |
// Must support old IE (so no Selectors API (matchesSelector) or anything) | |
// Can you shorten this? | |
var addEvent = (function () { | |
if (window.addEventListener) { | |
return function (el, ev, fn) { | |
el.addEventListener(ev, fn, false); | |
}; | |
} else { | |
return function (el, ev, fn) { | |
el.attachEvent('on' + ev, function() { | |
return fn.call(el, window.event); | |
}); | |
}; | |
} | |
}()); | |
var uls = document.getElementsByTagName('ul'); | |
for ( var i = 0, len = uls.length; i < len; i++ ) { | |
addEvent(uls[i], 'click', function(e) { | |
var target = e.target || e.srcElement; | |
if ( target && target.nodeName.toLowerCase() === 'a' ) { | |
// proceed | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Or, if we need multiple element event binding...
})();