Hosting Solutions  
 
   |  Tutorials Home  |  Privacy | 









Secured by RapidSSL



5 ~ Functions

(1)    (2)    (3)    (4)    (5)    (6)    (7)    (8)   

Functions are a little intimidating to most "javascript" beginners, but there is really no need to worry about them. Functions are simply a segment of code that can be comprised of one or more regular "javascript" 'commands' that can all be triggered to work together for some purpose.

Functions come in two parts; the function itself should usually go in the head tags of the document, and the command that triggers it can be placed just about anywhere you need it. This latter part, that triggers, or summons the function into action is nothing but the name of the function, followed by a set of parenthesis than may or may not contain parameters (data). The function is not executed when the page is loaded, unless the onLoad event is used in the body tag, or the summoner is placed inline somewhere in the body; it will just sit there and do nothing until it is triggered.

Since you are somewhat familiar with alerts from the preceding lesson, let's demonstrate the use of a function to fire up an alert window.


First, here's the code for the button that triggers the function:

<form>
<input type="button" name="demo1" value="Click Me"
onClick="demo1()">
</form>

This is the function itself:

<script language="Javascript">
<!--hide
function demo1()
{

alert("You used an onClick event handler to start the function that opened this window.")
}
//-->
</script>

The trigger for the function named 'demo1', is simply the name of the function, which was activated with the onClick event. You can trigger a function with almost any event, or simply by putting the name of the function where you want it in your document.

The function itself should go in the head section of the document, as with most all functions. This ensures that it is loaded and ready to go as soon as its trigger is activated in your html doc. I named this function 'demo1' arbitrarily; you can give your function any name you want, preferrably a descriptive name, but don't use any "javascript" keywords as the name or you'll get an error.

Functions are declared like variables are; you just write 'function' and then the name you give your function with the '()' immediately after the name. With this function, we are did not pass any parameters, so we left the parentheses empty-- but they must still be there all the same.

Notice the use of the brackets '{' and '}'... these are used for all functions and indicate the beginning and ending of the code that makes up the 'working' part of the function. Almost any "javascript" command can be used inside a function, and this greatly increases the versatility of "javascript". Let's try another function, one that will do a couple of different things. This will open another alert window like the first one, and then it will perform a second task as soon as the alert is closed.

When you close the alert window, take a look at the status bar at the bottom of this main window. The text produced there is from the second command in the same function. Here's the code:

<script language="Javascript">
<!--hide
function demo2()
{
alert("Yes, it's me again.");
defaultStatus=
"This is how you write text down here."
}
//-->
</script>

A simple function, but there's an important point to remember here: the text was not written until the first part of the function was finished with its execution, by closing the window. After the alert was finished, then the text was printed. There is another important item to take note of, and that's the semicolon (in red) immediately after the first statement. A semicolon denotes the end of one statement or command and the start of the next- since the defaultStatus line is the last one, it needs no semicolon.

One of the nice things about functions is that they can be used over and over with different parameters passed to them. Here is a function that can be used for as many different calculations as you want. Go ahead and click the button and enter a different number each time.

Here's the code.

<script language="JavaScript">
</--hide

function cm(inches)
{
var x=prompt('Please enter the number of Inches you want to convert to Centimeters')
var temp=x*2.54
alert(x+" inches is equal to "+temp+" centimeters.")
}

//-->
</script>

Yes, it's a little more complicated, but don't worry; we'll just take it apart a bit at a time and see how it works. First, we triggered the function with this code:

<form>
<input type="button" name="demo3" value="Click Me" onclick="cm()">
</form>

Notice that this function will have parameters (data, remember?) passed to it, but the parameter is not passed to it from the onclick event itself, so the parenthesis are empty. This event only takes us to the function, where the first variable definition in the function also triggers a prompt event. This prompt event is used to obtain the parameter, the number of inches, and pass it into the function.

Next in line is the variable declaration for 'temp', which is defined as x (The value you entered in the prompt window) times 2.54, the number of centimeters in an inch. The asterisk (*) is the multiplier operand in "javascript" and most programming languages, by the way. So far then, we have gotten our parameter from the prompt event, and the variable temp is defined as being the product of the parameter from the prompt window multiplied by 2.54

The next thing our function comes to is an alert which prints the result of the equation, the variable 'temp' in its window. Not really so mystifying after all, is it?

Spend some time experimenting with this function. See if you can add another parameter to it, or change things around and run it to see if your changes will work. This 'playing around' with scripts is the best way to learn. This script should also show you the versatility of functions; look closely and you'll see that this single function does five different tasks: it defines the variable 'x', triggers a prompt at the same time, defines the variable 'temp' that also performs an equation, an fires up the alert to give the product of the conversion.




Finally, as we near the end of this lesson, let's make a "javascript" clock. This is really in the area of advanced programming, but I know that almost everyone will be disappointed if I don't show how it's done and at least try to make it understandable. Take a look at the code for the function first, and then we'll go into some detail about the code.

<script language="Javascript">
<!--hide
var timerID = null;
var timerRunning = false;
function stopclock ()
{
if(timerRunning)
clearTimeout(timerID);
timerRunning = false;
}
function showtime ()
{
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds()
var timeValue = "" + ((hours >12) ? hours -12 :hours)
timeValue += ((minutes < 10) ? ":0" : ":") + minutes
timeValue += ((seconds < 10) ? ":0" : ":") + seconds
timeValue += (hours >= 12) ? " P.M." : " A.M. "
document.clock.face.value = timeValue;
timerID = setTimeout("showtime()",1000);
timerRunning = true;
}
function startclock ()
{
stopclock();
showtime();
}
//-->
</script>

That was a long one, wasn't it? First, notice that have several functions combined in this script. The first two variables you see above are simply used to initialize the clock.

In the function stopclock(), the global variable 'timerID' stores the identifier for the timeout. The timeout stops the clock until the next event happens (a new second transpires). This timeout is set for 1000 ms, or one second. Then the function showtime() updates the time and a new second is displayed, and on and on. The variables 'hours', 'minutes' and 'seconds' will be explained in Lesson 7 which has to do with dates and time. And finally the function startclock() starts the whole routine over again.

The call for this function is the event handler onload and should be placed in your body tag after your other body tag statements:

<BODY onload="startclock(); timerONE=window.setTimeout">

The onload event handler will start the script as soon as the page loads. The output of the clock script goes into a form window. You can put the code for this form window wherever you want your clock to be. Here it is:

<form name="clock" onSubmit="0"> <input type="text" name="face" size=13 value="">
</form>

That's about it for functions. Take the first couple of examples and make a minor change ot two of your own, then run them in your browser. When you can do this and not get an error, go on to the third example and experiment with it until you begin to feel more or less at ease. As you gain more experience, you will be surprised at how often you will get new ideas to add to your scripts. You may be surprised at how soon you will get to the point of writing your own fairly complex functions. Practice and experimentation is the key.


[Printer Friendly Page]


Lesson 6

(1)    (2)    (3)    (4)    (5)    (6)    (7)    (8)   





Updated on Thursday, 01~26~2012

Copyright © 1998 - 2012
Bill Payne & Sitebilder© Network