addEvent() new style

Introduction

This is the short version of my latest addEvent implementation stripped down to the essentials that should work crossbrowser.

Also check out the version based on Dean Edward's code.

The JavaScript code

/**
  * Generic add/removeEvent functionality
  *
  * @author Tino Zijdel ( crisp@xs4all.nl )
  * @version 1.2 (short version)
  * @date 2005-10-21
  */
function addEvent(obj, evType, fn)
{
	var evTypeRef = '__' + evType;

	if (obj[evTypeRef])
	{
		if (array_search(fn, obj[evTypeRef]) > -1) return;
	}
	else
	{
		obj[evTypeRef] = [];
		if (obj['on'+evType]) obj[evTypeRef][0] = obj['on'+evType];
		obj['on'+evType] = handleEvent;
	}

	obj[evTypeRef][obj[evTypeRef].length] = fn;
}

function removeEvent(obj, evType, fn)
{
	var evTypeRef = '__' + evType;

	if (obj[evTypeRef])
	{
		var i = array_search(fn, obj[evTypeRef]);
		if (i > -1) delete obj[evTypeRef][i];
	}
}

function handleEvent(e)
{
	e = e || window.event;
	var evTypeRef = '__' + e.type, retValue = true;

	for (var i = 0, j = this[evTypeRef].length; i < j; i++)
	{
		if (this[evTypeRef][i])
		{
			this.__fn = this[evTypeRef][i];
			retValue = this.__fn(e) && retValue;
		}
	}

	if (this.__fn) try { delete this.__fn; } catch(e) { this.__fn = null; }

	return retValue;
}

function array_search(val, arr)
{
	var i = arr.length;

	while (i--)
		if (arr[i] && arr[i] === val) break;

	return i;
}

Example

This is the original markup and menuhandling javascript of the contest page written bij PPK; I only changed the CSS to make it a more pretty example that behaves and looks pretty much the same in most browsers. This menu doesn't work perfectly and is only intended to demonstrate that the addEvent and removeEvent functions are working properly (here is an example of a better working menu, although this only uses the DOM level 0 event model).

Remove border/background effect.

Contact

If you have any questions regarding this page, please feel free to sent me an email.

September 9, 2005 - Tino Zijdel ( crisp@xs4all.nl )

Last changed: October 21, 2005 - created a short version that also works crossbrowser