Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

JavaScript Tutorial Part II - Function Basics

By Will Bontrager
2004-06-14


How to make your own functions

Here is a function template:

function blahblah() {
alert("This is function blahblah() speaking!");
}

The first line of functions you create must contain the word "function", a space, and then the name you assign to your function. The open curly brace character can follow on the same line or be placed on the line following.

Below the open curly brace is the function body, those lines of program code that will be run when the function is called. Immediately below the function body is a close curly brace.

In the above example, the function name is: blahblah()

The function body between the open and close curly braces in the example is composed of one line which calls a built-in function. So when you call blahblah() an alert box appears with: This is function blahblah() speaking!

You can call your function blahblah() from an HTML anchor link such as

<a href="javascript:blahblah()">click here</a>

(Notice how the browser is told it is a link to a JavaScript function rather than to a regular URL.)

Or, you can call your function with a form button such as

<form>
<input type="button" value="Click!" onClick="blahblah()">
</form>

(Because the word "onClick" is JavaScript code, the browser knows blahblah() is a JavaScript function -- and when it doesn't find a built-in function by that name it looks for one you created.)

Your functions can call built-in functions and they can call functions you make. Example:

function example() {
alert('Here!');
blahblah();
alert('Back to you...');
}

When you call the example() function, it first displays an alert box with: Here! then it calls your blahblah() function which displays an alert box with: This is function blahblah() speaking! and after that, it displays an alert box with: Back to you...

The ability to call other functions from within functions that you create is highly advantageous.

Consider that your program might have a dozen or so functions, most of which require a specific action as part of their larger purpose. Let's say that action is calculating the number of milliseconds that have elapsed since the visitor arrived at your page.

So you make a function to do the calculation, called elapsedmilliseconds(). Now, instead of writing the code to do the calculation in each of your other dozen functions, you just call the elapsedmilliseconds() function where appropriate.

Here is what a set of code might look like:

<script name="JavaScript">
<!--
var Now = new Date(); // Grab the current date.
var Start = Now.getTime(); // Initialize variable Start
// with the # of milliseconds
// elapsed since 1Jan70.
// (Netscape chose 1Jan70 as
// a standard date from which
// to do JavaScript time
// calculations.)
//
// See "Useful stuff to do
// with variables," in a
// section of this article,
// below, for an explanation
// of how the "Now" and
// "Start" variables are
// assigned their values.

function elapsedmilliseconds()// Calculates elapsed time
{
var n = new Date(); // Grab new copy of date
var s = n.getTime(); // Grab current millisecond #
var diff = s - Start; // Calculate the difference.
return diff; // Return the difference.
}

function decider()
{
var d = elapsedmilliseconds();
if(d < 600000) { alert("Elapsed milliseconds: " + d); }
else { window.location = "http://willmaster.com/"; }
}
// -->
</script>

<form>
<input type="button" value="Check Elapsed Milliseconds"
onClick="decider()">
</form>

When the page first loads, it assigns the current (this moment) date/time value to the variable Now. Then it uses that value to determine the current millisecond number with which to initialize the variable Start.

When you click the "Check Elapsed Milliseconds" on your page, it calls your decider() function. decider() calls the function elapsedmilliseconds() to determine the number of milliseconds that have elapsed since the page was first loaded -- when the variable Start was initialized.

When elapsedmilliseconds() is called, it determines the difference between it's own calculation and the value stored in the variable Start. It stores the result in variable diff.

Then elapsedmilliseconds() returns the value of the variable diff, which is what decider() assigns to its own variable d.

Last, decider() decides whether or not the page has been displayed a total of less than 10 minutes (600,000 milliseconds). If true, it displays an alert box with the value stored in d. Otherwise, it sends the visitor off to http://willmaster.com/

Hopefully, this has given you a glimmer of what is possible. Not only can you call your elapsedmilliseconds() function whenever you want, but other functions can call it, too, and make decisions based on what it returns.

Further elaboration and uses for program decision and flow control statements such as if(), for(), and while() will be in another section of this tutorial series.

(By the way, it took me 243740 milliseconds to write the above seven paragraphs while eating three small handfuls of popcorn.)

Let's suppose you want to modify your decider() function so you can tell it how many seconds to wait before sending the visitor off somewhere. And let's suppose you also want to tell it the location of that somewhere.

So you will modify your decider() function to accept a number (for the number of seconds) and a string of characters (for the URL). It will also be modified to use those data units where appropriate.

Here is the modified decider() function:

function decider(s,url)
{
var d = elapsedmilliseconds();
s = s * 1000; // s multiplies itself by 1000
if(d < s) { alert("Elapsed milliseconds: " + d); }
else { window.location = url; }
}

The decider() function receives two units of data when it is called, the number of seconds and the url, and stores them in variables s and url, respectively.

The variable "d" is then compared with "s" to see whether the alert box is displayed or the visitor is redirected to the value in "url".

You can call your modified decider() function with

<form>
<input type="button" value="Check (90 seconds)"
onClick="decider(90,'http://mydomain.com/')">
<input type="button" value="Check (45 seconds)"
onClick="decider(45,'http://mydomain.com/')">
</form>

or with

<a href="javascript:decider(90,'http://mydomain.com/')">
(90 seconds)</a>
<a href="javascript:decider(45,'http://mydomain.com/')">
(45 seconds)</a>

The above will send your function either the number 90 or the number 45 (for the number of seconds) and the string of characters http://mydomain.com (for the URL).

In a later article of this series, you will learn how to type stuff into a form (such as the number of seconds and the url, for the above example) and send that data to the function -- rather than hard-coding the data into a link.

And, you will often want to display function results in ways other than plain alert boxes.

Future articles will help you build popup boxes with your own design, on demand. They will help you display text and graphics on your page depending on which browser your visitor is using, depending on a name typed into a form, or other decisions your custom functions make.

Much of what you do with JavaScript depends on your program making decisions based on the contents of variables:

if([something]) then do this, else do that.

while([something]) do this.

for([each of a series]) do this.

The next article deals with those and other methods of program flow control.

Tutorial Pages:
» JavaScript Tutorial Part II - Function Basics
» Using/Calling functions
» How to make your own functions


Copyright 2004 Bontrager Connection, LLC


 | Bookmark
Related Tutorials:
» JavaScript Debugging Techniques with Firebug
» Striped Tables Using JavaScript
» Opening PDFs in a New Window with JavaScript
» Essential Javascript -- A Javascript Tutorial
» Submit Forms Conditionally using JavaScript
» How to Setup a Randomising Function

Ask A Question
characters left.