Before getting into the addEvent function, we should say a few words about default actions and preventing them. This will alter your strategy on binding handlers and writing them.

Some events like the click event of a link or submit event of a form have a default action. In the case of a link, the default action requests the URL referenced in the href attribute. The logic in the handler of any event determines whether or not the default action occurs. For a link whether or not the URL should be requested; The default is to execute the default action, and some code is required to prevent it.

Event handlers bound inline or by assignment return false to prevent the default action (true to do the default action). In the case of the link, the action is requesting a URL; a form onsubmit event submits data with a request for the URL in the action attribute.

That is fairly straight forward until we come to handlers bound by the addEventListener or attachEvent methods. Handlers bound with either of these methods must use the event object to prevent the default action. For IE's event object, set the returnValue to false, and for W3C DOM compliant browsers call the event object's method preventDefault().

The event object can be used to prevent the event's default action for all binding methods. However, older code intended for either inline or assignment binding frequently returns a boolean and is not a good candidate for binding via a method (without editing). Also, inline handlers are often short snippets or functions that don't access the event object. While IE has a global event object, Mozilla's event object is an agrument to the handler, and inline functions must use the key word "event" as a formal parameter on the call; as onclick="return myFnc(event);". So editing this legacy code requires changes to the code and each page where it is called. This can be a significant project on a large site.

The addEvent and removeEvent functions we're created with a boolean flag to force binding by assignment for situations where legacy code has to be manipulated.

This Demo2 link provides a demonstration of returning a value to prevent default action. The function test1() is bound inline, click the link and see that the default action doesn't occur. Below, view the code by clicking "Show Handler". Then, with "Bind to Property" checked, click "Remove", and test and view the handler. With "Bind to Property" uncheck, click Add. Test again, and view the handler.


You should notice 2 things:

The event object resource, e.preventDefault() has to be used to prevent default action in non IE browsers if the event handler has been bound using addEventListener. In IE the returnValue assignment will override the returned value, but if it is not set the return value is used to determine if the default action should run.

Returning false only prevents the default when the handler has been bound to the object's event by assignment or inline; or the browser is IE.