Adding Events in JavaScript
Every once in a while I have to do a little bit of javascripting in a project that is too small to use some dedicated libraries like jQuery, Prototype or MooTools but is big enough that requires me to add custom even handlers there.
As fun as it may be you need to be careful when doing it as there are some possible pitfalls. What are those? Well, there are few:
- no easy way to test if element has an event assigned
- risk of overwriting handlers
- different browsers means different ways to actually get the job done (here is looking at you IE)
This is why it is always helpful to have this following piece of code for unobtrusive and cross browser adding and removing events. Code was originally written few years ago by the one and only John Resig but it is still awesomely cool and easy to use.
So without further hesitation, here are two important methods: addEvent and removeEvent.
addEvent (obj, type, fn)
Parameters:
- obj - element that event will be registered to
- type - type of the event
- fn - function that will be launched upon the event
Code:
function addEvent(obj, type, fn){
if (obj.attachEvent) {
obj['e' + type + fn] = fn;
obj[type + fn] = function(){
obj['e' + type + fn](window.event);
}
obj.attachEvent(’on’ + type, obj[type + fn]);
}
else
obj.addEventListener(type, fn, false);
}
removeEvent (obj, type, fn)
Parameters:
- obj - element that event will be registered to
- type - type of the event
- fn - function that will be launched upon the event
Code:
function removeEvent(obj, type, fn){
if (obj.detachEvent) {
obj.detachEvent(’on’ + type, obj[type + fn]);
obj[type + fn] = null;
}
else
obj.removeEventListener(type, fn, false);
}
Usage:
addEvent(document.getElementById('my_elem'),'click',foo);
And that is pretty much it. Just copy and paste it to your project and have fun with it.
About this entry
You’re currently reading “ Adding Events in JavaScript ” an entry on GregWolejko.com
- Published:
- 7.22.08 / 8pm
- Category:
- JavaScript
GregWolejko







3 Comments
Jump to comment form | comments rss [?] | trackback uri[?]