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 :
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!")
}
test()
Now the function is "summoned", and you will see the words "Hello there!"
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
function area(w1,w2,h)
{
var area=(w1+w2)*h/2
alert(area+" sq ft")
}
area(2,3,7)
area(5,7,4)
area(3,2,1)
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.
Another reminder: Look at: alert(area+" sq ft"). How can we add characters? Well, in JavaScript, we could, and the result is the combination of the two strings into one. For example: alert ("Hi there"+" What is your age?") is the same as: alert("Hi there What is your age?")
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:
<script>
var x=prompt("Please enter your age")
function calsecs(age)
{
var temp=age*365*24*60*60
alert("You have lived "+temp+" seconds!")
}
calsecs(x)
</script>
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!
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)
{
temp=2*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:
<script>
var d=diameter(5) //d will contain 10
var a=3.14*diameter(5) //a will contain
31.4
</script>
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)
{
temp=2*x
temp2=2*2*x
return temp
return temp2
}
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:
onClick="alert('hello!')"
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. |
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: |
<script>
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")
}
</script>
<form>
<input type="button" name="test" value="Click me" onclick="inform()">
</form>
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" onclick="document.bgColor='lightblue'">
<input type="checkbox" name="C2" onclick="document.bgColor='lightyellow'">
input type="checkbox" name="C3" onclick="document.bgColor='lightgreen'">
</form>
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.
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:
<html>
<head><title>Body onload example</title></head>
<body onload="alert('This
page has finished loading!')">
Welcome to my page
</body>
</html>
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
directly the JavaScript code within the handler :"status='Do not click here, its empty!';return true"
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
calling it:.
function writestatus()
{
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:
onclick="document.write('hello')"
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: | ||||||||||||||||||||||||||
|
|
Ok then, lets go on and have a look at forms and how to access them using JavaScript.