Technology Programming

JavaScript By Example

Some HTML elements have a default action associated with them. In the case of an <a> tag the default action is to load the page referenced by the href attribute. In the case of a form the default action is to submit the form to the server side processing referenced in the action attribute. When we attach JavaScript event processing we may decide that the JavaScript processing is a replacement for the default action instead of an addition to it.


We therefore need a way from within the JavaScript to tell the browser that the default action is not required.

With the old style event handlers all we had to do to prevent the default action from happening was to return false. The more modern method of attaching events is made more complex by the fact that there can be multiple functions attached to the same event and element. As with the other event processing we have already looked at there are two different ways to prevent the default from occurring depending on the browser.

In this example we add a function to our script that allows us to call stopDef(); from within any function so as to prevent the default action for the element that the function is attached to from running.

stopDef = function(e) {
if (e && e.preventDefault)
  e.preventDefault();
else if (window.event && window.event.returnValue)
  window.eventReturnValue = false;
};
 
stopDef();



Leave a reply