Lesson 4-Functions & event handlers
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 codes are entered here
Lets do a basic example:
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:
Now the function is "summoned", and you will see the words "Hello there!"
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/2
alert(area+" sq ft")
w1, w2, and h are what the function use to store the input it receives from outside the function. They are the parameters. In the first function call, w1=2, w2=3, and h=7
You can have as many parameters as you like; of course, you have to specify that in your function. In this case, there are three: w1, w2, and h.
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")
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!
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:
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:
Introduction to Event Handlers
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:|
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" onclick="inform()">
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)
<input type="checkbox" name="C1" onclick="document.bgColor='lightblue'">
<input type="checkbox" name="C2" onclick="document.bgColor='lightyellow'">
input type="checkbox" name="C3" onclick="document.bgColor='lightgreen'">
I've put the actual demo of this example onto another window. Click the button to see it.
|Click here for output:|
We used the onclick handler to change the background color. See, we used a property of the document object to actually do something interesting. Notice that we just wrote in plain English the name of the bgcolor...you can do that, for most colors.
This is a crudely implemented bgcolor changer. Whenever you select additional checkboxes, the previous one stays checked. You can use buttons or radio boxes to alter that.
onLoad Event handlers
<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.
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.
the "status" refers to window.status, which is how you write to the status bar.
Note that instead of calling a function, we wrote
This is ok, but it is important that you separate statements with ;. You could have,
alternatively, written everything up until "return true" as a function and then
status="Do not click here, its empty!"
and then: onmouseover="writestatus();return true"
So you're thinking, "what is return true?" Good question. You need to add this line of code to set the status property with the mouseover effect. Uh? I know, don't worry so much now, it really isn't important. Just remember you need this to "activate" the status onmouseover effect. Later you will see how return (true/false) is used to stop links, forms from completing, but that's all not of any interest to us now.
onmouseout="status=' '" clears the status after the mouse leaves the link. Whenever the mouse moves away from the link, the status bar is "reset" again. If you don't insert this code, the status bar will still have those words you entered into it even after taking away the cursor.
Whenever we have nested quotations, the inner ones
are always singled. Ie:
<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...
|Event Handlers||Can be used with these tags:|