Javascript  
documentation WebMonkey JavaScript Tutorial

JavaScript CheatSheet

client-side
programming

DHTML - Dynamic HTML - implemented by using a client-side programming language to run scripts on the fly on the clients machine.

JavaScript - Created by Netscape Communications (supported by most browsers) but be careful - browsers and versions of browsers do not support it the same... test it on many browsers, many platforms. 

VBScript - Created by Microsoft (works only with IE)

 

Types of scripts:

Automatic - execute without the visitor doing anything

Triggered - visitor does something to trigger the script

 

basic syntax JavaScript is case-sensitive

JavaScript statements end with a semi-colon;

JavaScript uses the curly braces { } to block statements

Automatic script syntax:

Script is loaded and executed depending on where it is in the HTML file (usually put in the head between the </title> and </head> tags)
Script tags surround the inline script

    <script   language="JavaScript"   type="text/javascript">

        ...script

    </script>

can call an external script  (Macs may not support this)

    <script   language="JavaScript"  
                 type="text/javascript"  src = "extscript.txt">

    </script>

 

Comments:

// - comments text from slashes to end-of-line character

/*  comment */  - encloses a multiline comment between the /* and */

 

hiding the script Hiding scripts from older browsers:

After the <script...> tag
        <!--

                ...write the script

        //  some comment indicating the end of this comment -->

</script>
 

alert method alert("text to display");

Example:

<script language="JavaScript" type="text/javascript">
<!-- hide me

alert("this is a textbox");


// end hide -->

</script> 
 

 

JavaScript
example

Try This:  Example 1

Create an XHTML file in notepad named js_ex1.htm.  The script should display three alert boxes with three different phrases.  Make sure to test your script using Internet Explorer. The XHTML is as follows:

<html>
<head>
<title>Automatic  JavaScript Exercise</title>

<script language="JavaScript" type="text/javascript">
 <!-- hide me
//  Insert 3 alert boxes that have three separate phrases.

 



// end hide -->

</script> 

</head> 

<body> <h1>Yup! I know how to execute alert boxes!</h1>
<hr>
</body>
</html>

answer here: js_ex1.htm

variables Data types:

Four scalar types:

  • boolean (true or false)
  • numbers
  • string (single or double quotes)
  • null (no value at all)

Variables are typically not typed but the data type is determined at runtime.

Variables are usually declared through a var statement:

   var   <variableName>;

 

Variable names:

Must begin with an alphabetic character or underscore, followed by alphanumeric or underscore.

The JavaScript variables use file scope.

 

Example:

    var x;    // declaration of x
 

   x = 17;
   
    x = "hello";
   

prompt method strVar = prompt("prompt message","default value for textbox");

Example:

<script language="JavaScript" type="text/javascript">
<!-- hide me

    var someVariable;

    someVariable = prompt("Enter your name","joe smoe");


// end hide -->

</script> 
 

-OR-

<script language="JavaScript" type="text/javascript">
<!-- hide me

    var someVariable;

    someVariable = prompt("Enter your name",""); // no default value


// end hide -->

</script> 

 

intro to
 DOM 
DOM - Document Object Model

            manipulating the items in a window.

 

Brief list of object hierarchy

  • window
    • location
    • frames
    • history
    • navigator
    • event
    • screen
    • document
      • links
      • anchors
      • images
      • filters
      • forms
      • applets
      • embeds
      • plug-ins
      • frames
      • scripts
      • all
      • selection
      • style sheets
      • body

Accessing the hierarchy - use the member selection operator (period)

Each member has elements & methods

Examples:

    document.writeln("hello");

    document.image1.src="redmm.gif";

 

variable
Example

Example 2: Strings and variables JavaScript Example

The following JavaScript uses the prompt method, the DOM, and the methods associated with strings.

<html>
<head>
<title>Examples of variables & strings</title>

<script language="JavaScript" type="text/javascript">
<!-- hide me

// get values

var name= prompt("Give me a name:","default value");
var verb= prompt("Give me a past-tense verb:","");
var adj= prompt("Give me an adjective:","");
var noun1 = prompt("Give me a noun:","");
var noun2 = prompt("Give me another noun:","");
var sentence = name+" "+verb+" to the "+noun1+" <br />The "+noun2+" was "+adj+".<br />";

// stop hiding me -->
</script>
</head>

<body>

<script language = "JavaScript" type="text/javascript">

<!-- begin hiding me

document.writeln(sentence);

document.writeln(sentence.bold());

document.writeln(sentence.toUpperCase());

document.writeln(sentence.fontcolor('red'));

// end hiding -->

</script> 

</body>
</html>

 

Another
variable
example

Try This:  Example 3

Create an XHTML file in notepad named js_ex3.htm.  The script should request the user enter his/her name.  Then print a welcome message that includes their name. Make sure to test your script using Internet Explorer. The XHTML is as follows:

<html>
<head>
<title>Examples of variables & strings</title>

<script language="JavaScript" type="text/javascript">
<!-- hide me

// declare a variable and prompt the user for his/her name



// stop hiding me -->
</script>
</head>


<body>


<h1>
<script language="JavaScript" type="text/javascript">
<!-- hide me

//write a welcome message that includes the users name



// stop hiding me -->
</script>
</h1>


</body>
</html>
 

answer here: js_ex3.htm

triggered
script

Triggered: (There are 18 predefined intrinsic events)

Client does something that triggers the script to execute.  Each event is indicated as part of the HTML tag information:

    event = "script"

Examples of events:
        ONMOUSEDOWN
        ONCLICK
        ONMOUSEOVER
        more...

        Certain EVENTS work with certain HTML tags.

Example:

 

triggered script
example

Example 4: Triggered JavaScript Example

<html>
<head>
<title>Triggered JavaScript Exercise</title>
</head>
<body>
<button type = "button"     name = "someName"
onclick ="alert('You just clicked your mouse button')">
Click ME
</button>

<hr />

</body>
</html>

 

 

Examine Rollover
from a previous lecture
Roll-Over Example 1

 

<html>
<head>
<title>Rollover Example 1</title>
</head>
<body bgcolor="#000080" text="#FFFFFF">

<a href = "http://global.mm.com"
ONMOUSEOVER="document.mm.src='redmm.gif' "
ONMOUSEOUT="document.mm.src='greenmm.gif' " >

<img border="0" src="bluemm.gif" NAME= "mm" alt="an m&m" />
</a>
</body>

</html>

 

DOM form
example

Example 5: DOM form example


<html>
<head>
<title>DOM using a form</title>
</head>
<body bgcolor="#FFFFFF" text="#000000" >

<h1>This Form uses form elements to change the background color</h1>
<br />
<hr />
<hr />
<br />

<form name="colorForm"
    onsubmit="document.bgColor = newColor.value; return false">

<p>Enter a color: 
<input type="text" name="newColor" value="yellow"    
    maxlength=10 size = 10    
    onclick="document.bgColor='yellow'" />


<input type="submit" value="change it" />

</p>

<p>Choose a radio button: 
<input type="radio" name="optionColor"  
    onclick="document.bgColor='red'" />  red
<input type="radio" name="optionColor"
    onclick="document.bgColor='blue'" />  blue
</p>

<p>Use a Checkbox: 
<input type="checkbox" name="cbGreen"
    onclick="document.bgColor='green'" />  green
<input type="checkbox" name="cbGreen"
    onclick="document.bgColor='white'" />  white
</p>

<br />
<br />
</form>
</body>
</html>

 

creating a condition

Relational operators:   ==, <, >, <=, >=, !=

Logical operators:   &&, ||

simple selection
statement
if

if (exp)
    statement;

 

if-else

if (exp)
    statement;
else
    statement;

 

if (exp)
    statement;
else if (exp)
    statement;
else if (exp)
    statement;
else
    statement;

selection
 example
Example 6: if-else JavaScript Example

 

<html>
<head>
<title>If-Then Exercise</title>

<script language="JavaScript" type="text/javascript">
<!-- hide me

var color = prompt("What color do you prefer, red or blue? ","");
var adjective;

if (color == "red") 
{
    adjective = "crazy";

else if (color == "blue") 
{
    adjective = "cool";
}
else 
{
    color = "neither";
    adjective = "confused"
}

var sentence = "You like " + color + "? I think you're " +
                        adjective + "!";

document.writeln(sentence.fontcolor(color));

// stop hiding me -->
</script>


</head> 

<body> 

</body>
</html>

 

loop  

while

while (exp)
    statement;

 

do-while

do
{
    statement;
} while (exp);

 

for

for (exp1; exp2; exp3)
    statement;

 

loop
example

Try This:  Example 7

Create an XHTML file in notepad named js_ex7.htm.  The script should request the user enter an integer number.  Then print the word hello that number of times.  Make sure each hello is on a different line. Test your script using Internet Explorer. The XHTML is as follows:

<html>
<head>
<title>Loop Example</title>

<script language="JavaScript" type="text/javascript">
<!-- hide me



// stop hiding me -->
</script>


</head> 

<body> 

</body>
</html>

 

answer here: js_ex7.htm

programmer defined
functions
Function definition - usually placed in the head portion of the web page

function functionName(parameter list)
{
statements ...
}

Calling a function -  can be done anywhere below the definition.  Use the function name followed by values or variables based on the list in the parameter list.  remember there is no data type requirement - just the number of arguments must match the number of parameters.

Value returning functions - if a function is returning a value simply place the return statement followed by the value/variable returned.  When calling this function the call should be place where the return value will be used (an assignment statement for example).

  Example 8: Function Example

 

<html>
<head>
<title>Javascript</title>

<script language="JavaScript" type="text/javascript">
<!-- hide me

function sayHello(name)
{
    msg = "Hello "+name+"! <br\>";
    document.writeln(msg);
}

// stop hiding me -->
</script>

</head>
<body >

<button style=" width: 167px; height: 40px"

onclick =
     "name = prompt('What is your name? ','');
      sayHello(name)" >

click me
</button>
</body>
</html>
 

 

  Example 9: Value returning Function Example

 

<html>
<head>
<title>Javascript</title>

<script language="JavaScript" type="text/javascript">
<!-- hide me

function sayHello(name)
{
    msg = "Hello "+name+"! <br\>";
    return msg;
}

// stop hiding me -->
</script>

</head>
<body >

<button style=" width: 167px; height: 40px"

onclick = "name = prompt('What is your name? ','');
               msg = sayHello(name);
               document.writeln(msg);" >

click me
</button>
</body>
</html>
 

 

dom
document
Some document objects can be referred to by array index or name

document.anchors
document.links
document.forms
document.images

Example:

document.anchors[2]  - third anchor tag in document
document.links[4] - fifth link object
docuement.forms[0] - first form in document
document.images[1] - second image tag in the document

document.Entry_Form - form named Entry_Form
document.mm1 - image named mm1

 

To determine the number of elements in the array use the property length:

document.images.length - number of images in the document

 

dom
document.links example
Example 10: Change Link JavaScript Example

 

<html>
<head>
<title>Javascript</title>
</head>
<body style = "font-size:16pt" >

<a href="http://www.edinboro.edu">
This text take me to the Edinboro home page
</a>
<br /><br />

<a href="http://www.google.com">
This text takes me to Google
</a>
<br /><br />

<a href="http://www.amazon.com">
This text takes me to Amazon
</a>
<br /><br /><br /><br />

<button style="width: 167px; height: 40px

   onclick =
     "i = prompt('Which anchor to change: ','');
      document.links[i-1].href = 'http://www.yahoo.com';" >

    Change link
</button>
</body>
</html>

 

DOM
document.images example
Example 11: roll-over example

 

<html>
<head>
<title>Rollover Example 3</title>
</head>

<body bgcolor="#000080" text="#FFFFFF">

<img border="0" src="bluemm.gif" name= "mm1" alt="an m&m"
onmouseover="document.mm1.src='redmm.gif' "
onmouseout="document.mm1.src='greenmm.gif' " />

<img border="0" src="bluemm.gif" name= "mm2" alt="an m&m"
onmouseover="document.mm2.src='redmm.gif' "
onmouseout="document.mm2.src='greenmm.gif' " />

<img border="0" src="bluemm.gif" name= "mm3" alt="an m&m"
onmouseover="document.mm3.src='redmm.gif' "
onmouseout="document.mm3.src='greenmm.gif' " />

<br />
<br />
<button style="color: #FFFFFF; width: 97px; height: 40px; background-color: #FF00FF"

    onclick =
          "for (i=0;i<document.images.length;i++)
                {document.images[i].src = 'bluemm.gif';}" >

    Reset Images
</button>
</body>
</html>

 

Form Validation Just as the forms can be accessed via an array index or by name so can the form elements:

document.forms[0].elements[0] - first form, first field element
document.forms[0].elements[3] - first form, fourth field element

document.Entry_Form.name_field -
                the Entry_Form field element name_field

document.Entry_Form.elements[2] -
                the Entry_Form third field element

 

Use length to determine number of form elements:

document.form[0].elements.length - number of elements in form[0]

 

form validation
example 1
Example 12: Checking Completeness of form Example

 

<html>
<head>
<title>Javascript</TITLE>

<script language="JavaScript" type="text/javascript">
<!-- hide me

function IsFormComplete()
{
    var index = 0;
    var FormOk = true;

 while ((index < document.forms[0].elements.length) && (FormOk))
 {
    if (document.forms[0].elements[index].value == '')
   {
      alert('Please enter the '+
             document.forms[0].elements[index].name +
             ' and try again.');
      document.forms[0].elements[index].focus();
      FormOk = false;
    }
    index ++;
 }
return FormOk;
}


// stop hiding me -->
</script>
</head>
<body>
<br /><br /><br /><br />

<form onsubmit = "return IsFormComplete();"  
                             action="js_fv_response.htm">
Enter your name: <input name="Your name">
<br /><br />
email address: <input name="email address">
<br /><br />
phone number: <input name="phone number">
<br /><br /><br /><br />
<input type = "submit" value="Check your form" >
</form>
</body>
</html>

 
form validation
example 2
Example 13: Checking form email value Example

 

<html>
<head>
<title>Javascript</TITLE>

<script language="JavaScript" type="text/javascript">
<!-- hide me

function IsFormComplete()
{
    var index = 0;
    var FormOk = true;

 while ((index < document.forms[0].elements.length) && (FormOk))
 {
    if (document.forms[0].elements[index].value == '')
   {
      alert('Please enter the '+
             document.forms[0].elements[index].name +
             ' and try again.');
      document.forms[0].elements[index].focus();
      FormOk = false;
    }
    index ++;
 }
return FormOk;
}


function IsEmailValid( ElemName)
{
  var EmailOk = true;
  var Temp = document.forms[0].elements[ElemName];
  var AtSym = Temp.value.indexOf('@');
  var Period = Temp.value.lastIndexOf('.');
  var Space = Temp.value.indexOf(' ');
  var Length = Temp.value.length - 1 ; // Array from 0 to length-1

  if ((AtSym < 1) || // '@' cannot be in first position
      (Period <= AtSym+1) ||
            // Must be atleast one valid char btwn '@' and '.'
      (Period == Length ) || // Must be atleast one valid char after '.'
      (Space != -1)) // No empty spaces permitted
    {
         EmailOk = false;
         alert('Please enter a valid e-mail address!');
         Temp.focus();
    }
    return EmailOk;
}


// stop hiding me -->
</script>
</head>
<body>
<br /><br /><br /><br />

<form onsubmit =
      "if(IsFormComplete()) return IsEmailValid('email address');
                                 else return false;"
       action="js_fv_response.htm">

Enter your name: <input name="Your name">
<br /><br />
email address: <input name="email address">
<br /><br />
phone number: <input name="phone number">
<br /><br /><br /><br />

<input type = "submit" value="Check your form" >

</form>
</body>
</html>