If you just want to add new event handlers without overwriting the existing event handlers, you can use addEventListener()
or attachEvent()
(for older versions of IE) instead of setting .onclick
, .onsubmit
, etc... to add a new event handler without affecting the previous event handlers.
Here's a simple cross browser function to add an event:
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
There is no cross browser way that I'm aware of from regular javascript to interrogate existing DOM objects to see which ones have regular javascript event handlers installed via addEventListener
or attachEvent
. If the event handlers are installed with jQuery, they can be interrogated via this technique.
There is some future spec work that has been done to add a property that would list all the event handlers, but I am not sure it is implemented yet. You can read more about that here.
For event handlers installed with onclick
, onsubmit
, onfocus
, etc..., you can check all existing DOM elements to see which ones have handlers assigned for those events and you can then hook them if you want to.
// add other events here you are interested in
var events = ["onclick", "onsubmit", "onfocus", "onblur"];
var elems = document.getElementsByTagName("*"), item;
for (var i = 0; i < elems.length; i++) {
item = elems[i];
for (var j = 0; j < events.length; j++) {
if (item[events[j]]) {
console.log("event handler for " + events[j]);
}
}
}