4 ms·
var listen = function(el, evt, cbk) { if (el.addEventListener) { el.addEventListener(evt, cbk, false); } else { el.attachEvent('
by oinksoft 15y ago
var listen = function(el, evt, cbk) {
if (el.addEventListener) {
el.addEventListener(evt, cbk, false);
} else {
el.attachEvent('on' + evt, cbk);
}
};
No jQuery or whatever necessary ... if all you're doing is basic event handling and you know how the DOM works for other things, it really isn't much trouble to include this and a couple other small functions in a one-off, and is far preferable to including a hefty all-purpose DOM abstraction library like jQuery or MooTools.
Their example including an ugly onclick attribute doesn't imply that that is the only way to do things, it merely demonstrates the absolute simplest way to use the library. Of course any fool can use a script that includes the function above and locates the element manually.
- tripzilch 15y ago> if all you're doing is basic event handling and you know how the DOM works for other things, it really isn't much trouble to include this and a couple other small functions in a one-off, and is far preferable to including a hefty all-purpose DOM abstraction library like jQuery or MooTools. Why is that far preferable? So you can throw out all that extra code as soon as your events have to actually do something, and you decide you do need jQuery? :) To be honest, I do the same thing. It starts off as a small project one-off, and I think nah I don't have to include jQuery for something small if I just code these tiny DOM helper functions. And there hasn't been a single time, when after an hour or so of coding, I didn't wish I had started out using jQuery right away :) But sometimes then it's already too far, easier to just kludge along and finish the task than include jQuery and rewrite all the code so far to use it. So how's this preferable again?