addEventSimple

Here are the addEventSimple and removeEventSimple functions I use when I need a bit of unobtrusive event handling.

function addEventSimple(obj,evt,fn) {
	if (obj.addEventListener)
		obj.addEventListener(evt,fn,false);
	else if (obj.attachEvent)
		obj.attachEvent('on'+evt,fn);
}

function removeEventSimple(obj,evt,fn) {
	if (obj.removeEventListener)
		obj.removeEventListener(evt,fn,false);
	else if (obj.detachEvent)
		obj.detachEvent('on'+evt,fn);
}

They're used like this:

addEventSimple(element,'click',functionname);
addEventSimple(document,'load',functionname2);

Now the element element gets an onclick event handler that fires function functionname, while the document gets an onload event handler that fires function functionname2.

Caveat: The this keyword, which ought to refer to the element you've set the event handler on, doesn't work in Internet Explorer.

Explanation

See section 7C of the book for a complete explanation of these functions.