School Map:
Home / Enroll
$ Student Records; Class
$ News @ LIVE
Tech Radio * Support/FAQ
| Store | FORUMS
Script School Course #7 - JavaScript - Week #2 |
Printable Version of this page HERE |
Last week we started using methods like alert( ) and write( ). Methods are built-in functions. We have seen functions (methods) that take in information and use it, such as alert("Important Message Here");. Functions can also return values back to Your script. (see parseInt and parseFloat) Functions are containers for lines of script that can be reused any number of times during a page view. This week we will see how to write our own Functions to do special things for our web sites. JavaScript functions are placed within <SCRIPT> tags in the <HEAD> of a HTML document.
We create functions with the following syntax:
function function_name ([argument][, more arguments])
{
[variable declarations]
statement;
[more statements]
[return [value or statement]]
}
Where italics indicate names You supply, bold indicates essential elements, and square brackets [ ] are optional elements.
Function names follow the same rules as naming variables, that is, alphanumeric characters and the underscore. You can't use a number at the beginning of the name or have spaces. Also see the list of forbidden key words, as first shown in Week 1. It's a good idea to use meaningful names for functions, that suggest action. Example 'doMailCheck'. Notice the 'camel back' style of capitalizing second and latter words, this is optional. Some prefer to capitalize the first letter or use underscores between words. The arguments, or parameters, follow variable naming style. If You are working for a company, get their style rules. Whatever style You use, be consistent.
The keyword function indicates the beginning of the function. After a space, we name the function then follow with opening and closing parentheses that may contain arguments. The curly {sometimes known as French} braces contain the block of lines of code in the function. The lines in the block are indented to make reading the code easier. Some prefer to have the first French brace at the end of the line with the function name, this is a matter of style. It may be easier to see missing braces with the style shown here. When we get into decision structures this may be even more apparent.
Let's take a look at a very simple function with the bare minimum elements:
In the <HEAD> within <SCRIPT> tags:
// blanks status bar
function noStatus()
{
window.status = '';
}
We begin with a comment to indicate the purpose of the function, this may be
quite detailed at times. Very complex scripts are often written as just a set
of comments indicating logic and purpose first. Then the actual code is filled
in. This is known as pseudo scripting and it can be a very useful strategy.
The keyword function is followed by the function name noStatus
then empty parentheses. The code block begins with a French brace.
One line of code containing our only statement sets the status parameter of
the window object to ' ' , a blank string. The line ends with a semicolon.
We complete the function with the closing French brace.
Now anywhere we want to set the status bar to a blank, we 'call' the function
by using it's name and a set of parentheses:
In the <BODY>:
<a href="javascript:void('')"> Mouse Over </a>
Functions can be called from Event Handlers, other functions and in scripts. Just write it's name and supply any necessary arguments.
Seem familiar so far? We have already called Methods, built-in functions,
this way - and even passed in arguments: window.status("Click NOW for something
great!!!");
We can rewrite this function as:
// shows message in status bar
function showStatus ( message )
{
window.status = ( message );
}
The function structure sets up an argument named: message
The expression within the function is passing the contents of message
to the status parameter of the window object.
Essentially, arguments in functions become variables in the function, and
are used like variables.
The scope - or area within the script where these arguments are available -
is limited to the block of code within the French braces of the function.
<a href="javascript:void('')"
onMouseOver="showStatus('Message in the status bar');
return true;"> Mouse Over </a>
In the <BODY> we call the function: showStatus('Message in the status bar') in the Event Handler: onMouseOver. This is done the same way we used methods before. Whatever is passed to showStatus('~~~') is used in the function. Since window.status = '~~~' requires a string, we pass a string, delineated by quotes, to our function, showStatus. In the function, the argument is passed, like a variable, without quotes. Note: As discussed last week, be careful not to nest double quotes directly inside double quotes or single quotes directly inside single quotes!
In the syntax for functions shown above, the optional [variable declarations] indicates that variables can be declared within functions. Variables declared within functions have a scope limited to the block of code within the French braces, like arguments. In JavaScript, variables declared outside functions have 'Global Scope' and can be used anywhere in the script, including inside functions. However, if a variable is declared within a function with the same name as a Global Variable, it is the one used within the function. We'll see variables declared and used inside functions in a bit, stay tuned.
The keyword return stops the script at that point, and returns a value or the value of a statement, if there is one. Functions can return values to scripts using return followed by a space and then a value. Note: Global Variables - those declared outside functions - can be seen and have their values changed inside functions. The new value of the Global Variable is then available to JavaScript during the current page view. However, this can lead to problematic 'spaghetti code'. Usually it is better to pass values in through arguments and returning values with return. Doing so keeps Your code 'modular' and allows the reuse of Your functions in other scripts. Try to write functions that operate like 'black boxes' that do specific tasks, irregardless of the script they are in.
To see how functions return values to be used in scripts or in other functions we will take a look at some examples. They may seem complex initially, just follow the path through them and it should become clear. No point in speaking 'baby talk' forever. After all, You want to learn how to create, or at least understand, scripts that do some practical things, right? First, however, let's toss a few more JavaScript methods into our bag of tricks:
window.prompt("Your Instructions", "Initial Value")
Often in scripts it is necessary to do one thing or another depending on the value of a variable. The if structure allows us to do this.
In it's most basic form:
if (value comparison operator value)
{
do this
}
Comparison Operators Operator Definition (return true if:) == equal (two '=' characters) < less than > greater than <= less than or equal >= greater than or equal != not equal
For Joining Comparison Tests: && and (all comparisons must be true) || or (if any of the comparisons is true) (The || is two upper case of the backslash \ characters.)
For example, assume the variable age has been given a value from a prompt (or form - to be discussed soon), and we have already transformed the string input into a number with see parseInt or parseFloat. Assume also that the variable ageok has already been defined to be used as a flag.
if (age >= 18)
{
ageok = true;
}
Further on in the script the ageok variable flag is used to allow them in or whatever. But what if they are not greater than or equal to '18'? That's where an else clause comes in:
if (age >= 18)
{
ageok = true;
}
else
{
ageok = false;
}
If ageok is false we might want to send them elsewhere!
Say there are two conditions which must be met, the second involving the time of day in 24 hour notation as hour and we've defined another variable as flag timeok (we'll be looking at Time and Date in just a few moments)
if ((age >= 18) && (hour >= 22))
{
ageok = true;
timeok = true;
// let them in!!!
}
else if ((age >= 18) && (hour < 22))
{
ageok = true;
timeok = false; // tell them to come back later
}
else if ((age < 18) && (hour > 22))
{
ageok = false;
timeok = true;
// Tell them it's past their bedtime!!!
}
else
{
ageok = false;
timeok = false;
// Young but still early enough, send them to an age appropriate site!!!
}
As You can see, we've slipped in another term: else if and the use of multiple comparison tests joined by the && operator. When we get to the else clause, all other combinations have been checked so we know what to do. else clauses don't have comparison tests! The extra internal parentheses are not necessary in this situation, but are included for clarity. You always need the outer parentheses, and inner ones when creating logical groups. (see details below)
if (value comparison operator value)
// use as many comparison tests as You need,
// surround all with parentheses: ((a < b) || (c < d))
[ && or || (value comparison operator value)]
{
do this [optional nested if structure]
}
// use as many optional else if's as You need
else if (value comparison operator value)
// use as many comparisons as You need, see above
[&& or || (value comparison operator value)]
{
do that [optional nested if structure]
}
// optional else clause - one per nest
else
{
do default [optional nested if structure]
}
Where bold is required; Elements inside square brackets [] are optional (if used, their bold elements are required - don't include the square brackets!); italics indicate names or expressions You supply. If using additional comparisons, surround all of them with parentheses: ((a < b) || (c < d))
As soon as all of a comparison block evaluates to true, if structures run the associated do this or do that or perhaps run an optional else {do default}, and then the script leaves the if structure and continues on below it. Only one do this, do that or do default will run. It is not necessary to include any else if or else sections, either can be used without the other. The else block runs if nothing is true above it.
if structures may be nested inside other if structures as many levels deep as You need. Nested if structures are placed in the do this, do that or perhaps in the do default section. Each nest can have as many else if sections as You want, but only one if and one else.
You can have as many (variable comparison operator value or variable) comparison tests as You need before a do this or a do that. Comparison tests are joined with && (and) or || (or) operators. Comparison tests joined by && or || may be grouped inside parentheses. Groups themselves are joined by && or || operators. In such cases each group evaluates to true or false. This allows multiple comparisons to be checked before deciding if a block of statements is run or skipped. Put Your least likely to be true comparison first in && joins, if false, the script will skip the rest of the block. For || comparisons, put the most likely to be true first. The outer, main set of parentheses for a comparison block is always required.
if structures can be used inside functions, functions can be called from if structures. As with functions, indent Your code within the French braces for easier reading.
Seem complex? We'll see some more examples in the sections below... It's not difficult... Just a lot of repeating patterns...
JavaScript has built in methods to get the time and date the user has set on their machines. They are only as accurate as the user's settings. The Timer functions allow for elapsed intervals, and are as accurate as the user's hardware. It is also possible to set date and time objects for use within scripts, perhaps from a server script, but You're still counting on unreliable user settings for their time zone! Although these are serious limitations, these methods are often used for many non-critical operations.
The JavaScript Date object is similar to the Image object in that an instance of it is created and stored in a variable using the keyword new.
var now = new Date( );
The variable now has the time and date of the moment of it's creation, according to user settings. We can also set a date instance by passing arguments to the Date( ) object with (year, month, monthday, hours, minutes, seconds, milliseconds) the last 4 are optional but if any are included, all the larger intervals must be also:
var specialevent = new Date(2004, 9, 31, 10, 0);
As You can see we left off the seconds and milliseconds, these will be filled in with zeroes automatically. Most number series in JavaScript begin with zero, in the Date object January is 0. However for the monthday, the count begins at 1.
You can set and get the various aspects of a Date instance in Local Time or UTC (Universal Coordinated Time). (both are dependent on user settings)
We'll see an example using the Date() object at the end of this week's class.
JavaScript has two built-in window methods that run functions after an amount of time set in milliseconds. There are 1000 milliseconds in a second. setInterval() does this repeatedly while setTimeout() runs the function only once. Their syntax is as follows:
/* runs myFunction() every 200 milliseconds or 5 times a second: */ var myinterval = window.setInterval( "myFunction()", 200 ); /* runs myFunction() once after a delay of 5000 milliseconds or 5 seconds: */ var mytimeout = window.setTimeout( "myFunction()", 5000);
Notice that the function names are quoted as strings, while the number of milliseconds is not. You may wonder why we are setting these methods to variables. Both methods return a handle that can be used to stop them using the window methods clearInterval() and clearTimeout():
/* stops myFunction() from being called by setInterval() every 200 milliseconds: */ window.clearInterval( myinterval ); /* stops myFunction() from being called by the setTimeout() method: (if it has not run yet) */ window.clearTimeout( mytimeout );
If You use setTimeout to call the same function that it appears in, the function will be called again (and again) by setTimeout() after the delay time.
JavaScript can be used to help reduce the amount of bad data being sent to Your server through forms. By checking required entry fields You can also help the user fill out forms properly. Forms and their elements are integral to HTML.
Click HERE for a Form Verification Example.
Arrays are a type of variable that hold multiple, individually addressable values. They can have values added or removed after they have been created. Arrays are objects and can be created with the keywords new Array:
var myarray = new Array();
The following creates an array called myarray that has 6 empty elements:
var myarray = new Array( 6 );
However, If we supply a comma separated list instead of a single number, we declare and initialize the array with values:
var myarray = new Array( 3, 6, 9, 12, 15, 18 );
Another equal syntax for declaring and initializing arrays does not require the keywords new Array:
var myarray = [3, 6, 9, 12, 15, 18];
Elements of arrays are addressed numerically, beginning with zero. The array name is followed by square brackets containing the address number:
//Getting values: var element_zero = myarray[0]; // element_zero has the value of 3 var element_two = myarray[2]; // element_two has the value of 9 //Setting values: myarray[5] = 21;
Arrays can contain any type of value that a variable can, including boolians (true, false), null, integer and decimal numbers, objects and functions, and strings. Although most arrays are used to contain the same type of values, this is not required and types may be mixed within the same array.
You can get the number of elements in an array with it's parameter length:
var myarray_length = myarray.length;
Since array addressing begins at zero, the last element in any array is it's length minus one.
Within <SCRIPT> tags in the <HEAD>:
// Note: continue strings on the same line
// create array for Days:
var day = new Array('Sunday', 'Monday', 'Tuesday',
'Wednesday', 'Thursday', 'Friday', 'Saturday');
// create array for Months:
var month = new Array('January', 'February', 'March', 'April',
'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December');
// create new Date object instance as 'now'
now = new Date;
// operates Clock
function Clock ()
{
// make Clock() repeat every second (1000 milliseconds)
setTimeout("Clock()", 1000);
// update clock by one second
now.setTime(now.getTime() + 1000);
// get month as number
var mnum = now.getMonth();
// use mnum to get value from month array
var mthstr = month[mnum];
// get day of week as number
var dnum = now.getDay();
// use dnum to get value from day array
var dstr = day[dnum];
// get day of month as number
var dtstr = now.getDate();
// get year
var yr = now.getYear();
// get hours
var hrnum = now.getHours();
// change to 12 hour clock, find AM or PM
if( hrnum > 12 )
{
hrnum = hrnum - 12;
var sfx = "PM";
}
else if ( hrnum == 12)
{
var sfx = "PM";
}
else if ( hrnum == 0 )
{
hrnum = 12;
var sfx = "AM";
}
else
{
var sfx = "AM";
}
// get minutes as number
var minnum = now.getMinutes();
// format minutes as 0X if less than 10
if ( minnum < 10)
{
minstr = "0" + minnum;
}
else
{
minstr = minnum;
}
// get seconds as number
var secnum = now.getSeconds();
// format seconds as 0X if less than 10
if ( secnum < 10)
{
secstr = "0" + secnum;
}
else
{
secstr = secnum;
}
// create time string with all values
// continue strings (between quotes) on the same line
var timestring = dstr + " " + mthstr + " " + dtstr +
", " + yr + " " + hrnum + ":" + minstr + ":" + secstr + " " + sfx;
// show timestring in form text area
document.clock.clocktxt.value = timestring;
} //end of Clock() function
In the <BODY> : (Cascading Style Sheet and table formatting not shown for clarity)
<form name="clock" method="" action=""> <input name="clocktxt" type="text" class="clockstyle" size="44" maxlength="44"> </form>
Within the <BODY> tag itself, we start the clock when the page loads, using an onLoad Event Handler:
<BODY onLoad="Clock()">
We begin within <SCRIPT> tags in the head, and establish arrays to contain
the names of the days and months. Notice that these arrays are holding
string values, which are indicated by the single quotes surrounding each name.
If You don't quote them as strings, You will get an error. Then we create
a new instance of the Date object that contains the time of it's creation. Notice
the syntax does not use parentheses. Then the function Clock() begins
with the line: setTimeout("Clock()", 1000); This causes the function Clock()
to call itself every second. Each time the function runs, it calls itself again
one second later. The comments in the code explain the rest. Recall that
to address the text area in the form, which is a child object of the document
object, and set the text area's value parameter, use the syntax:
document.form.element.value = "string";
or in this case:
document.clock.clocktxt.value = timestring;
The Clock() function is called when the page loads, see above.
There will be no examples shown for the assignments this week, come to the chat workshops and use the forum for help.
In a form text area show: "Today is (name of day)... " and an appointment scheduled for that day. Use arrays to store the name of the days and the appointments.
Option #1: Create a countdown to an event. Show it as 'days' 'hours' 'minutes' 'seconds' left till EVENT. Set the EVENT for approximately two weeks after the assignment is turned in.
Option #2: Create a Tip of the Day script and show a different tip for each day of the week.
Option #3: Create a script you can use for your website which utilyzes the information in this Week 2 course text.
Need help with your assignment or have questions about the first week's course?
About The Instructors
TDavid is co-owner, programmer and webmaster for several sites devoted to programming including his own http://www.tdscripts.com/ He has done custom programming in various programming languages for companies all over the world. Every Friday at 2pm PST you can catch his weekly radio show dedicated to the technical side of webmastering and programming at http://www.scriptschool.com/radio/
LogSpirit is a student of Script School, the co-author of this course and available for hire for custom programming.
| Printable Version of this page HERE |
School Map:
Home / Enroll
$ Student Records; Class
$ News @ LIVE
Tech Radio * Support/FAQ
| Store
Advertising
| Link To Us | Privacy
Copyright 2000-2002 Script School Productions / KMR
Enterprises
No part of this website may be reproduced, copied and/or distributed
in any medium
without express written permission