So, what is an Event?

Event Handlers

Event Handlers are JavaScript methods, i.e. functions of objects, that allow us as JavaScript programmers to control what happens when events occur.

Directly or indirectly, an Event is always the result of something a user does. For example, we've already seen Event Handlers like onClick and onMouseOver that respond to mouse actions. Another type of Event, an internal change-of-state to the page (completion of loading or leaving the page). An onLoad Event can be considered an indirect result of a user action.

Although we often refer to Events and Event Handlers interchangeably, it's important to keep in mind the distinction between them. An Event is merely something that happens - something that it is initiated by an Event Handler (onClick, onMouseOver, etc...).

The elements on a page which can trigger events are known as "targets" or "target elements," and we can easily understand how a button which triggers a Click event is a target element for this event. Typically, events are defined through the use of Event Handlers, which are bits of script that tell the browser what to do when a particular event occurs at a particular target. These Event Handlers are commonly written as attributes of the target element's HTML tag.

The Event Handler for a Click event at a form field button element is quite simple to understand:

<INPUT TYPE="button" NAME="click1" VALUE="Click me for fun!"
 
onClick="event_handler_code">

The event_handler_code portion of this example is any valid JavaScript and it will be executed when the specified event is triggered at this target element. This particular topic will be continued in Incorporating JavaScripts into your HTML pages.

There are "three different ways" that Event Handlers can be used to trigger Events or Functions.

Method 1 (Link Events):

Places an Event Handler as an attribute within an <A HREF= > tag, like this:

<A HREF="foo.html" onMouseOver="doSomething()">   ...   </A>

You can use an Event Handler located within an <A HREF= > tag to make either an image or a text link respond to a mouseover Event. Just enclose the image or text string between the <A HREF= > and the </A> tags.

Whenever a user clicks on a link, or moves her cursor over one, JavaScript is sent a Link Event. One Link Event is called onClick, and it gets sent whenever someone clicks on a link. Another link event is called onMouseOver. This one gets sent when someone moves the cursor over the link.

You can use these events to affect what the user sees on a page. Here's an example of how to use link events. Try it out, View Source, and we'll go over it.

<A HREF="javascript:void('')"
 
onClick="open('index.htm', 'links', 'height=200,width=200');">How to Use Link Events
</A>

The first interesting thing is that there are no <SCRIPT> tags. That's because anything that appears in the quotes of an onClick or an onMouseOver is automatically interpreted as JavaScript. In fact, because semicolons mark the end of statements allowing you to write entire JavaScripts in one line, you can fit an entire JavaScript program between the quotes of an onClick. It'd be ugly, but you could do it.

Here are the three lines of interest:

  1. <A HREF="#" onClick="alert('Ooo, do it again!');">Click on me!</A>
  2. <A HREF="javascript:void('')" onClick="alert('Ooo, do it again!');">
    Click on me!
    </A>
  3. <A HREF="javascript:alert('Ooo, do it again!')" >Click on me!</A>

In the first example we have a normal <A> tag, but it has the magic onClick="" element, which says, "When someone clicks on this link, run the little bit of JavaScript between my quotes." Notice, there's even a terminating semicolon at the end of the alert. Question: is this required? NO.

Let's go over each line:

  1. HREF="#" tells the browser to look for the anchor #, but there is no anchor "#", so the browser reloads the page and goes to top of the page since it couldn't find the anchor.
  2. <A HREF="javascript:void('')" tells the browser not to go anywhere - it "deadens" the link when you click on it. HREF="javascript: is the way to call a function when a link (hyperlink or an HREFed image) is clicked.
  3. HREF="javascript:alert('Ooo, do it again!')" here we kill two birds with one stone. The default behavior of a hyperlink is to click on it. By clicking on the link we call the window Method alert() and also at the same time "deaden" the link.

The next line is

<A HREF="javascript:void('')" onMouseOver="alert('Hee hee!');">
Mouse over me!
</A>

This is just like the first line, but it uses an onMouseOver instead of an onClick.

Method 2 (Actions within FORMs):

The second technique we've seen for triggering a Function in response to a mouse action is to place an onClick Event Handler inside a button type form element, like this:

<FORM>
      <INPUT TYPE="button" onClick="doSomething()">
</FORM>

While any JavaScript statement, methods, or functions can appear inside the quotation marks of an Event Handler, typically, the JavaScript script that makes up the Event Handler is actually a call to a function defined in the header of the document or a single JavaScript command. Essentially, though, anything that appears inside a command block (inside curly braces {}) can appear between the quotation marks.

For instance, if you have a form with a text field and want to call the function checkField() whenever the value of the text field changes, you can define your text field as follows:

<INPUT TYPE="text" onChange="checkField(this)">

Nonetheless, the entire code for the function could appear in quotation marks rather than a function call:

<INPUT TYPE="text" onChange="if (this.value <= 5) {
     alert
("Please enter a number greater than 5");
}
">

To separate multiple commands in an Event Handler, use semicolons

<INPUT TYPE="text" onChange="alert(‘Thanks for the entry.’);
  confirm(‘Do you want to continue?’);
">

A Demo of the above code.

The advantage of using functions as Event Handlers, however, is that you can use the same Event Handler code for multiple items in your document and, functions make your code easier to read and understand.

Method 3 (BODY onLoad & onUnLoad):

The third technique is to us an Event Handler to ensure that all required objects are defined involve the onLoad and onUnLoad. These Event Handlers are defined in the <BODY> or <FRAMESET> tag of an HTML file and are invoked when the document or frameset are fully loaded or unloaded. If you set a flag within the onLoad Event Handler, other Event Handlers can test this flags to see if they can safely run, with the knowledge that the document is fully loaded and all objects are defined. For example:

<SCRIPT>

var loaded = false;

function doit() {
     // alert("Everything is \"loaded\" and loaded = " + loaded);
     alert('Everything is "loaded" and loaded = ' + loaded);
}

</SCRIPT>

<BODY onLoad="loaded = true;">
-- OR --

<BODY onLoad="window.loaded = true;">

<FORM>
     <INPUT TYPE="button" VALUE="Press Me"
      
onClick="if (loaded == true) doit();">
-- OR --
     <INPUT TYPE="button" VALUE="Press Me"
      
onClick="if (window.loaded == true) doit();">
-- OR --
     <INPUT TYPE="button" VALUE="Press Me"
      
onClick="if (loaded) doit();">
</FORM>

</BODY>

See this Example in "Action"

The onLoad Event Handler is executed when the document or frameset is fully loaded, which means that all images have been downloaded and displayed, all subframes have loaded, any Java Applets and Plugins (Navigator) have started running, and so on. The onUnLoad Event Handler is executed just before the page is unloaded, which occurs when the browser is about to move on to a new page. Be aware that when you are working with multiple frames, there is no guarantee of the order in which the onLoad Event Handler is invoked for the various frames, except that the Event Handlers for the parent frame is invoked after the Event Handlers of all its children frames -- This will be discussed in detail in Week 8.

Setting the bgColor Property

The first example allows the user to change the color by clicking buttons, while the second example allows you to change colors by using drop down boxes.

Event Handlers

EVENT

DESCRIPTION

onAbort the user cancels loading of an image
onBlur input focus is removed from a form element (when the user clicks outside the field) or focus is removed from a window
onClick the user clicks on a link or form element
onChange the value of a form field is changed by the user
onError an error happens during loading of a document or image
onFocus input focus is given to a form element or a window
onLoad once a page is loaded, NOT while loading
onMouseOut the user moves the pointer off of a link or clickable area of an image map
onMouseOver the user moves the pointer over a hypertext link
onReset the user clears a form using the Reset button
onSelect the user selects a form element’s field
onSubmit a form is submitted (ie, when the users clicks on a submit button)
onUnload the user leaves a page

Note: Input focus refers to the act of clicking on or in a form element or field. This can be done by clicking in a text field or by tabbing between text fields.

Which Event Handlers Can Be Used

OBJECT EVENT HANDLERS AVAILABLE
Button element onClick
Checkbox onClick
Clickable ImageMap area onClick, onMouseOver, onMouseOut
Document onLoad, onUnload, onError
Form onSubmit, onReset
Framesets onBlur, onFocus
Hypertext link onClick, onMouseOver, onMouseOut
Image onLoad, onError, onAbort
Radio button onClick
Reset button onClick
Selection list onBlur, onChange, onFocus
Submit button onClick
TextArea element onBlur, onChange, onFocus, onSelect
Text element onBlur, onChange, onFocus, onSelect
Window onLoad, onUnload, onBlur, onFocus