Mass Media For The Individual
Katy Whitton Web Development Logo
 
 
Tutorials - JavaScript - Lesson 7 - Functions and IF.... ELSE Commands

Functions are placed in the <head> tags of the document. They allow the user to type in one string of code that can be referred to (called) many times within one page. An example of a function would be:

function alertme( )
{
var ages;
ages=answer

if (ages<20)
{
alert('you are too young!');
}
else
{
alert('you are really old!');
}
}


Then, in the body section we call the function by placing it in an event handler (in this case onClick):


<a href="#" onClick="answer=(prompt('enter your age', ''));alertme();">click here for fun!</a>

This means that when the user clicks the link, a prompt box will appear asking the user for their age and then the function will be called. Click the link below for an example:

click here for fun!

Here's what the code does:

function alertme( ) Start the function and name it so it can be called later
{ Shows the beginning of the function's contents
var ages;  Set up a variable called ages
ages=answer set the value of ages to answer
if (ages<20)
if the value held in ages is less than 20
{
alert('you are too young!'); alert the user that they are too young
}
else else, if the values of ages is 20 or over
{
alert('you are really old!'); Tell the user they are too old.
}
}

As we saw before in tutorial 5, the input is gathered via a prompt box.

Functions are useful if you have many different sections of code that need to be called at different times. If...else statements are useful for validating user input, checking for browsers etc.

In Tutorial 8, we'll look at image a simple rollover

back
 
Tutorials

Customer Log-In
If you have purchased our software, enter your email address and password below to download it.