Lesson # 5 - Handling Events

# 5 Handling Events

# 5 Review Questions # 5 Assignment

Document Object Model

As you know, JavaScript is a product of Netscape, and you need to be familiar with the overall organization of how a browser sees a web page. Here is a chart that shows the hierarchy of elements that can be part of any browser window. Each of these objects has its own set of properties and methods that we can have a little fun with as programmers. Properties are attributes and methods are behaviors. Properties are like nouns and methods are like verbs in grammar. An example would be say, on a person object such as yourself, a property would be your hair, which could have values such as blond, curly, etc, and a method would be person.changeHairColor(), which you could use to change your hair color to purple if you should need to do that. Methods are always used with parentheses, even if the parentheses have nothing inside them!

You don't need to memorize the document object model, but study it a bit so that it makes sense.

There is a lot of information about these objects that we can't go into here, but you can always look up what you want to know. To access more information on the DOM, visit https://www.w3schools.com/js/js_htmldom.asp.

Note that window is the grand master of all other objects. It is the one that the browser treats as first and foremost. Even if the browser has no document loaded, the window object is defined in the browser's memory. The window object includes the content part of the window where all the documents get loaded, as well as such things as the dimensions of the window, and other 'window-trimmings' such as scroll bars, toolbars, status bar, etc. Frames behave roughly as if they were a window object. If we want to reference any method or property of the window object, the full and complete way to do that is by using the object name 'window' and the dot separator as in:

window.propertyName

window.methodName( [parameters] )

var newWindow = window.open("http://ths.ttsd.k12.or.us", "THSWindow", "width=300 height=200");

However, since the 'window' object is always the controlling object, it is acceptable to omit it and just refer directly to the property or method by name. You may also see the keyword 'self' substuted for the word 'window' refering the the window where the current document is loaded. For our lessons we will mostly take the easy way and just refer to the property and method directly.

An important thing to know is how we use this model to name elements on a web page. Suppose I have a web document that contains a form named myForm and that the form contains a text box named myTextBox. In order to refer to the value property of that element we have to use the syntax:

document. formname.inputname.value

or

document. myForm.myTextBox.value

Each type of object in the chart above has its own set of properties and methods. Events are specific to an object type, so you need to know which events you can control with event handlers. Here is Netscape's chart on the events. To create an event handler, we add an attribute to the object's tag and add the word 'on' to the front of the event, then put the JavaScript statements in quotation marks. . For example, for an image to do a MouseOver effect, we add 'onMouseOver = " JavaScript statements" inside the tag for that object. A complete example would look like this:

<IMG SRC="companylogo.gif" onMouseOver = "myJSFunction();">

JavaScript event handlers

Event Applies to: Occurs When Event Handler
Abort images User aborts the loading of an image (for example by clicking a link or clicking the Stop button)
onAbort
Blur windows and all form elements User removes input focus from window or form element
onBlur
Change

text fields,

textareas,

select lists

User changes value of element
onChange
Click buttons, radio buttons, checkboxes, submit buttons, reset buttons, links
User clicks form element or link
onClick
DragDrop windows User drops an object onto the browser window, such as dropping a file on the browser window
onDragDrop
Error images, windows The loading of a document or image causes an error
onError
Focus windows and all form elements User gives input focus to window or form element
onFocus
KeyDown
documents, images, links, text areas
User depresses a key
onKeyDown
KeyPress documents, images, links, text areas User presses or holds down a key
onKeyPress
KeyUp documents, images, links, text areas User releases a key
onKeyUp
Load document body User loads the page in the Navigator

onLoad
MouseDown documents, buttons, links User depresses a mouse button
onMouseDown
MouseMove nothing by default User moves the cursor
onMouseMove
MouseOut areas, links User moves cursor out of a client-side image map or link
onMouseOut
MouseOver links User moves cursor over a link

onMouseOver
MouseUp documents, buttons, links User releases a mouse button
onMouseUp
Move windows User or script moves a window
onMove
Reset forms User resets a form (clicks a Reset button)

onReset
Resize windows User or script resizes a window
onResize
Select text fields, textareas User selects form element's input field

onSelect
Submit forms User submits a form
onSubmit
Unload document body User exits the page
onUnload




Sample Events for Window

One of the more useful events for us to program for a window is when a document or web page fails to load. If you have a business you may still want customers to reach you, no matter what happens to a certain web page. Errors can occur as a result of a slow server or a slow connection. It would be nice to display a message and maybe an 800 phone number when and if a web site fails to load. This might be especially useful if you have recently made some changes and have doubts about everything working correctly. Could that ever happen? Ohhhhh yeah! All window event handlers are placed inside the Body tag. So something you might place in the <BODY> section would be an event handler such as this:

<SCRIPT >
<!-- hide javascript
onError = "alert('Our Web Site is having a bad day. Please call 1-800-999-9999 for service.');"
end hiding -->
</SCRIPT>

In the example above, notice the use of the single quotes around the alert message. This is because we are nesting the text of the alert message inside of the double quotes that contain the JavaScript statement itself. JavaScript requires that we alternate between single and double quotes so it can tell the difference.

Sample Events for Document

Something that many websites do is perform a certain function when a user closes a certain window. Usually it is opening a new window with an annoying advertisement, but you might as well see how it is done. the event is unload, so the event handler is onUnload. Here is a sample that will say goodbye to a user when they close your web page.

<SCRIPT >

<!-- hide javascript

document.onUnload="alert('Thank you for visiting Rock Candy Village today.')";

end hiding -->

</SCRIPT>

 

Sample Events for Form

Form object can be thought of as a container for all the text boxes, radio buttons, etc that manage the data on a form. Therefore they don't have a lot of event handlers. Forms can be referenced by the name that you give them in the name attribute, or by an index number inside of square brackets. Computers generally count starting with item 0, so if you name the first form on your document formLogin, then either of these two are equivalent ways to reference your form:

document.formLogin

document.form[0]

One example of an event handler is what to do when the user clicks on a Submit button. The event handler would be onSubmit. You might think it would be automatic for the onSubmit event handler to be called when a user clicks on Submit, but it is not automatic. You must explicitly code onSubmit = "..." within the <FORM> tag. Here is a sample form that asks for a name and account number. Since these area both important fields, the user should not be able to submit the form without filling in both.

<HTML>

<HEAD>

<TITLE> Login Screen </TITLE>

<SCRIPT >

function checkLogin(form){
    if (form.userName.value =="" || form.accountNumber.value == ""){

         alert("You must fill out both fields to continue.");
         return false;

    } // end of if block

    return true;

} // end of function checkLogin

</SCRIPT>

</HEAD>



<BODY>

<FORM onSubmit = "return checkLogin(this)">
Please login.  Fill out both fields.
Enter your name:<INPUT TYPE = "text" NAME = "userName"><BR>
Enter your account number:<INPUT TYPE = "text" NAME = "accountNumber"><BR>
<INPUT TYPE="submit">
</FORM>

</BODY>

</HTML>

When a user tries to submit this form, before it goes off to the server to be actually submitted, the function 'checkLogin()' is called.

There are some symbols here that deserve explanation. First, in the if statement, there are two conditions that are checked. If the userName field is equal to an empty string, or the accountNumber field is equal to an empty string then an alert will be given and the function will return false. Note that to compare we use a double equal sign ==. That is because a single equal sign means to assign a value to a variable on the left, so we use the double == to mean compare and see if the right and left sides are equal. The || symbol means 'OR'. The condition will evaluate to 'true' if one or the other is true, so if either field is left blank the user will be told to fill it in before proceding. If both fields are filled in. even with garbage values, the form will be sent to the server for further checking there.

Sample Events for <INPUT...> objects

These event handlers will be used quite often because they are so useful. They are included with the <INPUT> tag as an attribute. Here is a sample.

Shall we send you our catalog?<INPUT TYPE="checkbox" onClick = "alert('Thank you. We will mail it today!');">

Any of the other <INPUT> types would be fairly similar, and any of the JavaScript statements you have learned, and any you will be learning can be used. The alert() method could be replaced with any function name written by you, or any other built-in JavaScript method you want. Button objects will always have the 'onClick' event handler added, or why would there be a button there?

Return to Top of Page | Back to Main Menu