Javascript: Event defaults

There are a number of cases where you would be interested in stopping the default behavior of an event. The next listing includes code to stop the default link behaviour occuring when links are clicked:

addEvent(document.getElementById("stop-default"), "click", stopDefaultBehavior);
function stopDefaultBehavior (evt) {
  var eventReference = (typeof evt !== "undefined")? evt : event;
  if (eventReference.preventDefault) {
  else {
    eventReference.returnValue = false;

This approach uses something called object detection, to confirm that a method is actually available before it is called, which helps prevent possible errors. The preventDefault method is available in every web browser but Internet Explorer, and it prevents the default action of an event from happening.

If that method isn’t supported, it falls back to setting the returnValue of the global event object to false, thus stopping the default behaviour in Internet Explorer.

Leave a Reply