Learning Javascript

The Script Tag

Nearly all browsers interpret javascript, except the very early ones. Javascript is placed within an html file, between the <script> and </script> tags.

< script type="text/javascript">
... javascript code goes here ...
</script>

These scripts can be placed within the head or the body of the document. Scripts are placed within the head, when they contain functions or variable declarations, that should be available to the entire html document. Scripts containing executable code are placed within the body.

Variables, Type and Scope

Variable Names:

Simple variables in javascript can be of three types:

More complex data types can be built of these three types. These are called objects. Javascript contains several built in objects, or you can declare your own.

You do not declare variable types in javascript (except for objects). A variable takes on a type when you give it a value. It is perfectly legal to assign a string value to a variable of type number. The variable changes types when you do. This can become a bit confusing.

The typeof() function is useful for determining the type of variables. An example of its use:

document.write(typeof (x));

Though you do not declare variable types, you can declare variables. If a variable is declared within a function, it is local to that function, and cannot be used outside the function.

Does a Variable Exist

Test for existence of a variable from JSKit If its data type is "undefined":. if (typeof x=="undefined") alert("\"x\" doesn't exist!") ...

Comments

// is used to comment out a single line.

Number Operators

Number Operators operate on numbers.
+ sum
- difference
* product
/ quotient
% remainder
++ increments by 1
-- decrements by 1

String Operators

There is only one string operator. It concatenates strings.

Strings are enclosed within quotation marks. Either single or double quotes can be used.

Number Assignment Operators

= is replaced by
+= is increased by
-= is decreased by
*= is multiplied by
/= is divided by
x%=y x is replaced by x%y

String Assignment Operators

= is replaced by
+= is concatenated by

Statements

Assignment operators are used to make statements. Statements should be separated by semicolons. The following are valid javascript statements.
x=2;
x+=5;
c="bunnies";
d="Easter";
d+=" ";
d+=c;

Comparison Operators

== is equal to
=== is equal to and has the same type
!= is not equal
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to

Conditionals

if (x==y) {statements} else {other statements}

AND
if ((x==y)&&(i==j)){statements}

OR
if ((x==y)||(i>j)){statements}

NOT
if !(x===y){statements}

Character Representation in JavaScript

CharacterRepresentation
newline\n
'\'
"\"
\\\

Objects in Javascript

String
Number
Boolean
Array
Image
Date
Math
Object
-- All the above objects must begin with a capital letter. --

The Html DOM is an object in javascript. Thus we have the window object, the document object, and all the objects they contain.

Top Level Functions -- work on all objects

FunctionUsage
eval(Astringofcommands) evaluates string of commands and executes it.
number()Creates a number from a string.
string()Creates a string from a number.

Image Objects

myImage=new Image(x,y); where x,y are the width and height of the image.
myImage.src="rainbow.gif";

The parentheses following the new keyword invoke the constructor method. It creates a new instance of the image object. When you identify the image file by giving its source, the image file with all its properties is loaded into memory.

This image object is NOT the same as Html's. The only two properties of JavaScript's image object which can be changed are src and lowsrc. Furthermore it must be CAPITALIZED, thus: Image() More on Image objects: WebReference Preloading

Object Objects
myFamily=new Object();
myFamily.sister="Mary";
myFamily.brothers=[Jim,Herb];
The parentheses invoke the constructor method to create a new type of object, whose structure will be determined by the . commands you use to give it properties and values.

The Math Object

The Math object has these properties (or constants):
Math.E
Math.PI
Math.SQRT2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

and these methods (or functions):

Math.sin()
Math.cos()
Math.tan()  

Math.asin()
Math.acos() 
Math.atan() 
Math.sqrt() 
Math.exp() 
Math.log() 

Math.round() 
Math.ceil()
Math.floor() 
Math.abs() 
Math.random() 
Math.fixed() 

Math.eval() 

Math.max() 
Math.min()

The Html DOM Object

The html document object model (DOM) is an object in javascript, which means that all of its objects and methods can be used in javascript.

Some of those useful in output are:

window.alert("Any text message can go here.");
document.write("some text", "some more text", "etc", "<br>");
window.print("");
window.confirm("");
window.prompt("");

The document.write statement accepts variables, text in quotes, and html tags in quotes.

Use document.write( ) to generate repetitive html code

The document.write( ) method can be used to write html code into your document, which will then be interpreted as html. Note the careful change of quotes from double to single with nesting.

<script type="text/javascript">
document.write("<table border='1'>");
for (var i=0; i<=3; i++){
  document.write("<tr>");
  for (var j=0; j<=2; j++){
    document.write('<td>', i, j, '</td>')
  }
  document.write('</tr>')
}
document.write('</table>');
</script>
Other DOM Methods
These methods are useful for referring to objects so that they can be modified, or otherwise manipulated. The setTimeout("fcn", ms) method waits ms milliseconds before calling function "fcn". The clearTimeout() method clears the corresponding setTimeout.
 x = setTimeout("fcn", ms)
 clearTimeout(x);

String Functions -- work on strings

String functions are methods of the String object. They are called by dotting them to a string or string variable. All strings and string variables can be treated as if they were String objects.

FunctionUsage
lengthReturns the number of characters in the string
replace('x','y')Returns a string in which the FIRST instance of 'x' has been replaced with 'y'
indexOf("st") Searches a string for the first instance of "st", and returns the index at which it was found. (The index of the first character is 0.)
substring(i, j)Returns the substring, beginning after the 'ith' and through 'jth' character.

Examples:

g="Hello".indexOf("e") returns the number: .

"0123456789".substring(2,4) yields the string: .

It is important to note that the statement

s="hohoho"; 
s.replace('o','O') 

does NOT change the value of s. To do so, one must write:

s="hohoho"; 
s=s.replace('o','O') 

Use of Regular Expressions to Extend the Usefulness of String Functions

Regular expressions can be used in pattern matching. A regular expression can be defined in either of two ways:

var x = new RegExp("o","g");
The first argument is the 'regular expression'. The second argument is a flag, which determines how broadly the regular expression is to be applied. The next definition of a regular expression is identical to the first.
var x = /o/g;

It is not essential to use regular expressions in pattern matching. They are often used because the optional arguments are convenient.

Escape Codes Used with Regular Expressions

CharacterRepresentationCommon Name
\\\backslash
/\/slash
.\.dot

Arrays in Java Script

Arrays of Numbers
I had some difficulty with defining arrays of numerical values. I couldn't say

var tiz = new Array(6)

like everyone says you can, because the browser thought I was defining a array with one element like this:

tiz[0] = 6

This seems to work, however:

var hh=new Array(0,0,0,0,0,0,0,0,0,0)
var ii=new Array(0,0,0,0,0,0,0,0,0,0)
var jj=new Array(0,0,0,0,0,0,0,0,0,0)
var kk=new Array(0,0,0,0,0,0,0,0,0,0)
Note: It appears that you have to spell Array with a capital A

You cannot try to save keystrokes and say:

x=y=new Array(0,0,0)

because then the two arrays will always have the same values.

Arrays of Strings
Here are two ways to define string arrays.
  var vegetable = new Array("artichoke","broccoli","carrot")
var fruit = new Array( );

fruit[0] = "apple";
fruit[1] = "banana";
fruit[2] = "cherry";
The for in method is useful when you want to do something to each element of an array. Here we print them out.
for (var i in fruit){
document.write(fruit[i], "<br>")
}
for (var i in vegetable){
 document.write(vegetable[i], "<br>")
}

Fruits:

Vegetables:

Arrays of DOM Objects

The Html DOM contains the arrays:

However, arrays of any set of objects can be made by using the document methods: For example, here is a function which will form an array of all the <pre> tags used in the document.
function makePreArray()
 {preArray=document.getElementsByTagName("pre")}
Printing out the pre array for this file gives:
for (i in preArray) 
 {document.write(i,'  ',preArray[i],' ', preArray[i].tagName,' ', preArray[i].className, '................ ', typeof(preArray[i].tagName), ' ', typeof(preArray[i].className),'<br>')};

A nice feature is that length is included as an element of the array.

The types of tagName and className are string.

Choosing Elements of Various Types
Using getElementsByTagName("*") will produce an array of all tags in the document up to this point.

We can sort the resulting array by classes, tagNames, or any other property with an idea from Javascript Kit. For example here is a function that produces an array of all elements of the class "code".

function getElementsByClass()
{alltags = document.getElementsByTagName("*");
 var inc=0;
 for (var i in alltags)
   {if (alltags[i].className=="code")
        codedSegments[inc++]=alltags[i]
    }
 }
The resulting array is:

Java Script Reserved Words

Java script is case sensitive. All the reserved words must go in lowercase, unless noted otherwise.
abstract
boolean
break
byte
case
catch
char
class
const
continue
default
delete
do
double
else
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
while
with
this

Recursion -- Scrolling Images

These scrolling star images are from JavaScript Corral by Ray Stott, 1998.

First the images are written into the document using a for( ) statement. Note how the images line up beside one another. They are inline elements like text.

The value of a is determined by the Html DOM's document.images[ ] array. The one previous image on this page is document.images[0]. The first image in the scroller will be document.images[1]. Thus a = 1.

<script type="text/javascript">
  var a = 1;  //array index of first image in group
  b = 12;    //number of images to be displayed
  for (var i=a; i<a+b; i++)
  {document.write('<img src="scrollimg1.gif" width=34 height=33>')
  }
</script>

The function startImageScroll() creates two instances of the image object, and loads them with the filenames of the two images to be used. This causes the image files to be loaded by the browser, ready for immediate use. This step should be done before the images are written into the document. There won't be time when the scroller starts changing images every 1/10 of a second. This can be accomplished by calling the startImageScroll() when the document is loaded. Then startImageScroll() calls the function imageScroll().

function startImageScroll()
   {i = a;  //index of first image to be scrolled
    blueStar = new Image();
    rainbow  = new Image();
    blueStar.src = "scrollimg1.gif";
    rainbow.src  = "scrollimg2.gif"; 
    imageScroll();
    }  

The function imageScroll( ) uses the document.images[ ] array of the Html DOM. It changes the ith image to a rainbow, and the (i-1)th image to a blue star. Then it increments i, and uses setTimeout to wait 100 milliseconds, before calling itself again.

function imageScroll( )
   {    //change ith image to a rainbow
    document.images[i].src = rainbow.src; 
       //change preceding image back to a blue star
    if(i>a)
      document.images[i-1].src = blueStar.src
    else
      document.images[a+b-1].src = blueStar.src;
       //increment i; 
      //if at end of line, go back to beginning.
    if (++i==a+b)
      i = a;
    setTimeout("imageScroll( )", 100);
    }