First, the usage syntax of the code is something like this:
Code:
var element = document.getElementById("myID");
function ABCs() {
alert("Now I know my ABC's!!!");
}
addEvent(element, "click", ABCs)
//Or if you want to capture the event with non-IE browsers: addEvent(element, "click", ABCs, true);
As for the code itself, I'll try walking you through it with comments:
Code:
function addEvent(el, type, func, bool) {
if(window.addEventListener) el.addEventListener(type, func, !!bool);
//Checks to see if the method of adding events is through addEventListener or attachEvent.
//The !!bool is to turn bool into false if undefined or false, or into true if set to true.
//Note that I don't have to do fancy legwork with reordering events here, as it is already FIFO.
else {
//IE way of adding events and making LIFO into FIFO
type = "on" + type;
//IE wants an argument like "onclick" vs "click"
if(el.events===undefined) el.events = [];
//Gives the element a property to record what events have been assigned to it because you can't tell otherwise (or at least I don't think so).
for(var e=el.events, i=e.length-1; i!=-1; --i) {
//Looks through the element's event property that I had created and sets a loop to get rid of all its events.
//Note that this loop could easily look like for(var i=0, e=el.events; i<e.length; i++) and do the same thing.
//Also, if this is element currently has no events, this is bypassed.
el.detachEvent(e[i][0], e[i][1]);
//(Remember e=el.event.) e is an array that has length equal to the number of events the element has. e[i] stores the event type (e[i][0]) and the function (e[i][1]), so el.detachEvent() can remove the event.
//The event is removed in the first place to restack the event pile later in the code by readding them in the "correct" order.
}
el.events.push([type, func]);
//Records the new event into el.events
for(var e=el.events, i=e.length-1; i!=-1; --i) {
//With the previous loop it did not matter whether it incremented or decremented. In this case, it has to decrement because we have to reverse LIFO into FIFO
el.attachEvent(e[i][0], e[i][1]);
//Adds the events in "reverse" order to make it FIFO
}
}
}
Bookmarks