header.gif (6771 bytes)

Lesson 4-Functions & event handlers

Now that we've learned the fundamental structure of JavaScript programming, lets move down the hierarchy and poke at two other important aspects of JavaScript- functions and event handlers. In this section, we'll look at :

Red_CurlyC035.gif (285 bytes) Functions and creating your own functions

Ok, what are functions? Well, functions are chunks of code that together achieve a more complex task, and are not executed until you call upon them. Its like your trusted car-It can take you places, but it only does that when you drive it-it does not start driving by itself. Unlike regular lines of codes, the execution of them are deferred until you want them to.

The basic syntax of a function is:

function whatever_name()
function codes are entered here

Lets do a basic example:

function test()
document.write("Hello there!")

We've just   created a simple function. Note that if only this were within your <script></script> tags, you will not see "Hello there" on your screen. Like the car you own, it does not drive by itself. To "drive" it, you have to call it. Take a look:

function test()
document.write("Hello there!")

Now the function is "summoned", and you will see the words "Hello there!"

Red_CurlyC035.gif (285 bytes) Functions with Parameters

The beauty of functions is that it can receive data from the "outside" world and process it. The term parameter is used as a definition for "what goes into the function." You can supply different data into the function each time. What this means is that you can create one function, and use it over and over again. An example should clear up this. Lets do an example that calculates the area of a trapezoid. The formula is : (width1+width2)*height/2tri.gif (1964 bytes)

function area(w1,w2,h)
var area=(w1+w2)*h/2
alert(area+" sq ft")

You are not limited to passing actual values into a function that accepts parameters. You can also pass in variables can contain these values. This adds flexibility to your functions. Lets look at an example of such that'll demonstrate this concept:

var x=prompt("Please enter your age")
function calsecs(
var temp=age*365*24*60*60
alert("You have lived "+temp+" seconds!")

Notice that we passed in x into the function, which can change each time a person enters a different age. One important thing to take notice is that the actual variable name that's passed in, "x", is not, and does not have to be the same name represented in the function. For example, instead of using "x", we used the name "age" in the declaration of the function . The name "age" is simply a placeholder that "holds" the actual variable that gets passed in. Simply put, the two names do not have to be the same, despite the fact they represent the same "thing". Lets say I call the function above another three times:

calsecs(z) //this time, "age" holds the variable "z"

calsecs(w) //this time, "age" holds the variable "w"

calsecs(m) //this time, "age" holds the variable "m"!

If the two names have to be the same, then you are restricted to passing only that variable in, instead of "z", "m", "w", or whatever you want!

Red_CurlyC035.gif (285 bytes) Functions that return a value

Ok, I know you're sick and tired by now of all the function talk, but this will be the last one, and a very important one indeed. One thing to realize is that a function itself can return a value. Lets see what I mean:

function diameter(x)
return temp

Look at the part in red. This function will take in a radius of a circle, and return the diameter. Lets see how this function may be used in a script:

var d=diameter(5)
//d will contain 10
var a=3.14*diameter(5)
//a will contain 31.4

See, by setting a function to return a value, the function itself becomes, in a sense, a variable that will store what the function itself returned. Is, and why is this useful, you ask? Because now you can have a function process something, return the "processed goods", and have the script continue on manipulating that variable. Normally, once a function processes something, the processing of that "something" ends there. BTW, if you didn't get a thing I just said in the last sentence, don't worry about it! Just know how to return a value from a function, and sooner or later, you will wonder how you lived without this knowledge for so long. One thing to take note: A function can only return one value, just like a variable can only contain one value at a time. For example, the following is illegal:

function illegal(x)
return temp
return temp2

Red_CurlyC035.gif (285 bytes)Introduction to Event Handlers

So, what are event handlers? Very powerful and useful! They are JavaScript code that are not added inside the <script> tags, but rather, within you html tags, that execute JavaScript when something happens, such as pressing a button, moving your mouse over a link, submitting a form etc. The basic syntax of these event handlers is:

name_of_handler="JavaScript code here" For example:


Event Handlers:

onclick:   Use this to invoke JavaScript upon clicking (a link, or form boxes)
onload:   Use this to invoke JavaScript after the page or an image has finished loading.
onmouseover:   Use this to invoke JavaScript if the mouse passes by some link
onmouseout:   Use this to invoke JavaScript if the mouse goes pass some link
onunload:   Use this to invoke JavaScript right after someone leaves this page.

Red_CurlyC035.gif (285 bytes)onClick Event handler

Ok, lets see how the onclick event-handler can help us. Remember, any event handlers are added inside html tags, not inside <script></script> ( there is an alternate way, which will not be discussed in this section). First of all, does that mean we can simply dump event handlers anywhere within any html tag? Noooo! onClick handlers execute something only when users click on form buttons, check boxes, etc, or text links, therefore they can only be inserted in these tags, for example, <a>,<input type=..>. Lets see an example of an onClick event handler:

Click here for output:

function inform()
alert("You have activated me by clicking the grey button! Note that the event handler is added within the event that it handles, in this case, the form button event tag")

<input type="button" name="test" value="Click me"

The function inform() is invoked when the user clicks the button.

All examples you have seen up to now use this handler, the onClick handler, to illustrate the examples. Ok, let me show you another example that will make use of the checkbox element.

Try this: (it will change the background color of a document interactively)

<form name="go">
<input type="checkbox" name="C1"
<input type="checkbox" name="C2"
input type="checkbox" name="C3"

I've put the actual demo of this example onto another window. Click the button to see it.

Click here for output:

Red_CurlyC035.gif (285 bytes) onLoad Event handlers

The onload event handler is used to call the execution of JavaScript after a page /frameset /image has completely loaded. It is added like this:

<body onload="inform()"> //Execution of code //will begin after the page has loaded.

<frameset onload="inform()"> //Execution of code //will begin after the current frame has loaded.

<img src="whatever.gif" onload="inform()"> //Execution of code will begin after the image //has loaded.

Lets see an example of an onload handler:

<head><title>Body onload example</title></head>
<body onload="alert('This page has finished loading!')">
Welcome to my page

As soon as the page has finished loading, it will alert you saying so.

Red_CurlyC035.gif (285 bytes) onMouseover,onMouseout

These handlers are used exclusively with links (the onmouseover/onmouseout image effects is derived from this, which we will talk about later). The following example writes something to the status bar (at the bottom of your screen) whenever a mouse cursor hovers over the link, and deletes it when the mouse moves away.

Output: Dont't Click Here

<a href="blabla.htm" onmouseover="status='Do not click here, its empty!';return true" onmouseout="status=' '">Don't Click Here</a>

Several new concepts arise here, so I'll go over each one of them.

Red_CurlyC035.gif (285 bytes) onUnload

onunload executes JavaScript immediately after someone leaves the page. A common use (though not that great) is to thank someone as that person leaves your page for coming and visiting.

<body onunload="alert('Thank you. Please come back to this site and visit us soon, ok?')">

There are other event handlers, many belonging to forms, so I will defer the discussion of them until we get there...

Again, for convenient reference, here is a complete list of all the event handlers in JavaScript:

Event Handlers Can be used with these tags:

windows, all form elements, frames
buttons, radio buttons,
checkboxes, submit buttons,
reset buttons, links
text fields, textareas, select lists
windows, images
windows, frames, and all form elements
body, images
areas, links
text fields, textareas
submit button

Ok then, lets go on and have a look at forms and how to access them using JavaScript.

Lesson 5