onClick ()

 

The old way (DOM Level 0):

<INPUT TYPE="BUTTON" VALUE="Calculate" NAME="calcButton" onClick="calculate()">

That was called an "event handler" and it relied on fitting JavaScript code into your HTML elements. The code above called the calculate() function when someone clicked the button defined by that HTML tag. The problem with DOM Level 0 is that there's really no way to associate multiple functions with a single event. You have to create some sort of master function that's called by the event handler and, in turn, calls the other required functions.

The new way, defined by DOM Level 2, relies on event listeners, several of which can be associated (the term is "registered") with a given object and a given kind of event.

document.calcForm.calcButton.addEventListener("click", function(e) {calculate()}, false);

What's that all about?

  1. Well, the addEventListener() method associates a function with an event. In the example above, a "click" event is associated with the calculate function().
  2. What is e? That variable contains an object representing the event itself.

    If we had needed to, we could have sent e (and therefore the object it contained), or a part of it, to the function like this:

    document.calcForm.calcButton.addEventListener("click", function(e) {calculate(e.target)}, false);

    That would send the name of the clicked button to the function -- handy if it were responsible for reacting differently to clicks on different buttons.

  3. What is the "false" argument for? It specifies that this function does not capture the event and stop it from bubbling up through the object model (to the form, for example, which, if you think about it, was also clicked and could also have an event listener for "click" events). A "click" event is one of the events associated with Button objects

 

 

Name: