Handling events

 

  <html>
 <head>
 </head>
  <body>
   <script language="JavaScript">
         alert('hello world')
  </script>
 </body>
</html>  

 

TrYit: As an exercise, use the HTML script element in the body section of an html document to write "hello world". You can Use the JS example to the right. Note: use a plain text editor.

Now that you are familuar with,

  1. JS syntax,
  2. when to execute JS,
  3. the HTML section in which scripts are placed, and
  4. how to execute internal script in the body section.

it is time to show how JavaScript functions in the head section of an html document are triggered using HTML event handlers as attributes.

Using event handlers

JavaScript event handlers can be divided into two parts:

  • Interactive event handlers - is the one that depends on user interaction with the form or the document (e.g. <p onClick ="execute function">TRYIT).
  • Non-interactive event handlers - automatically executes JavaScript code without the need for user interaction (e.g. <body onLoad="execute function">).

Event handlers are JavaScript code that are added inside html tags, that execute JavaScript when something happens, such as

  • pressing a button (e.g onClick),
  • moving your mouse over a link (e.g. onMouseOver),
  • submitting a form (onSubmit) etc .

The basic syntax of these event handlers is:

eventHandler="JavaScript Code"              or onClick="Compute"

In this example the eventHandler is the name given to the particular event handler such as onClick, and JavaScript Code represents the name of a function that you have written in JavaScript. For example, say you defined a function called Compute in the head section of a HTML document. You could have Navigator perform this function when the user clicks on a button with an HTML tag that looks like this:

<INPUT TYPE="button" VALUE="Calculate" onClick="Compute(this.form)">

The event handler in this example is onClick, which calls the Compute function when the user initiates the event of clicking on a button. This is refered to as an interactive event handler since the user must do something.

 
Imsg
Discussion

Blogging

E-mail

 

JAVASCRIPT    -    LESSON 3
Event - Handlers