You are on page 1of 74

JavaScript Basics :

THE FIRST SCRIPT

- Printable Version - Send Page To Frien

Knowing that javascript needs to be entered between <script> tags, is a start. But
there are a few other things you need to know before writing your first javascript:

Javascript lines end with a semicolon. You may have noticed from the example on the previous page that javascript lines end with a semicolon. You can easily put all your javascript on a single line without destroying the performance of it. However, you would destroy the overview of your script so it is not advisable.

Always put the text within " ". When entering text to be handled by javascript, you should always put the text within " ". If you forget to enclose your text in " ", javascript will interpret your text as being variables rather than text. In the next section you will learn why this would cause an error to your script.

Capital letters are different from lowercase letters. You should always remember that capital letters are different from lowercase letters. This means that when you write commands in javascript, you need to type capital letters in the correct places, and nowhere else.

Incorrect capitalization is probably the most common source of error for javascript
programmers on all levels!!

Now consider this example: Instead of having javascript write something in a popup box we could have it write
directly into the document.
<html> <head>

<title>My Javascript Page</title> </head> <body> <script> document.write("Welcome to my world!!!"); </script> </body> </html>

The document.write is a javascript command telling the browser that what


follows within the parentheses is to be written into the document.

Note: When entering text in javascript you need to include it in " ".

The script in the example would produce this output on


your page:
Welcome to my world!!!

Consider this example to learn where javascript writes the text:


<html> <head> <title>My Javascript Page</title> </head> <body> Hello!!!<br> <script> document.write("Welcome to my world!!!<br>"); </script> Enjoy your stay...<br> </body> </html>

The output from this example would look like this:


Hello!!! Welcome to my world!!! Enjoy your stay...

As you can see, javascript simply writes the text to where the script is placed

within the HTML codes.

An interesting aspect is that you can write all kinds of HTML tags to webpages
with the document.write method.

For instance, if you wanted to make a long table that compared Fahrenheit and
Celsius, instead of actually typing all the values into the table, you could have javascript calculate the values and write the table to the document.

An example of a javascript generated table can be seen on the page explaining


the hexadecimal colorsytem.

On that page, there are 15 tables with 25 columns in each.


Each cell shows different mixtures of the basic colors red, green and blue.

To set up these tables in HTML would demand almost an entire days work. Using
javascript for the same purpose took less than 15 minutes!

JavaScript Basics :

CAPITAL LETTERS
It is extremely important to be aware that javascript makes a sharp distinction
between capital and lowercase letters.

Javascript does not consider a variable named myvalue to be the same as a


variable named MYVALUE.

Consider these examples:


Example 1
<html> <head> <title>My Page</title> </head> <body> <script> myvalue=2; myvalue=5; result=myvalue+myvalue; document.write(result); </script> </body> </html>

Example 2
<html> <head> <title>My Page</title> </head> <body> <script> myvalue=2; MyValue=5; result=myvalue+MyValue; document.write(result); </script> </body> </html>

The output of example 1 would be 10 (5+5). The output of example 2 would be 7 (2+5).

The best advice is to use the same syntax on all variables. Either write all variables in small letters, start with one capital letter or write all
variables in capitals.

Which syntax you chose is not important


- as long as you chose just one!

POP UP BOXES
It is possible to make three different kinds of popup windows. Try clicking the buttons below to see the differences:

- Printable Version - Send Page To Frien

ALERT BOX
The syntax for an alert box is: alert("yourtext"); The user will need to click "OK" to proceed. Typical use is when you want to make sure information comes through to the user. Examples could be warnings of any kind.
(Typical examples are "Adult Content", or technical matters like "This site requires Shockwave Flash plug-in").

CONFIRM BOX:
The syntax for a confirm box is: confirm("yourtext"); The user needs to click either "OK" or "Cancel" to proceed. Typical use is when you want the user to verify or accept something. Examples could be age verification like "Confirm that you are at least 57 years old"
or technical matters like "Do you have a plug-in for Shockwave Flash?"

- If the user clicks "OK", the box returns the value true.
- If the user clicks "Cancel", the box returns the value false.
if (confirm("Do you agree")) {alert("You agree")} else{alert ("You do not agree")};

Note: The if statement is explained later in this tutorial.

PROMPT BOX:
The prompt box syntax is: prompt("yourtext","defaultvalue"); The user must click either "OK" or "Cancel" to proceed after entering the text. Typical use is when the user should input a value before entering the page. Examples could be entering user's name to be stored in a cookie or entering a
password or code of some kind.

- If the user clicks "OK" the prompt box returns the entry.
- If the user clicks "Cancel" the prompt box returns null.

Since you usually want to use the input from the prompt box for some purpose it is
normal to store the input in a variable, as shown in this example:
username=prompt("Please enter your name","Enter your name here");

VARIABLES
Variables can be compared to small boxes with names.

- Printable Version - Send Page To Frien

If you were to store 5 pair of shoes, you might have a box for each pair. On each
box you would write what is in it.

The boxes would be your variables. - Places to store things.

The name on the boxes would be the variable names. - The ones you'd use when referring to each of the boxes.

And finally the shoes, would be the content of the variables. - What is stored in the boxes.

A variable is simply a place in the computer's memory to store information. All


variables are referred to by the unique name you assigned to them.

Consider this example:


<html> <head> <title>My Javascript Page</title> </head> <body> <script> myname="Henrik"; document.write(myname); </script> </body> </html>

This example would write "Henrik" in the document. Note that when you want text to be stored in a variable you need to put the text in

" ". The reason is that javascript uses " " to tell the difference between text and variables.

Look at this example to see the importance of this.


<html> <head> <title>My Javascript Page</title> </head> <body> <script> Henrik="my first name"; myname=Henrik; document.write(myname); </script> </body> </html>

Try to predict the output of the example before reading on. - In the first line, the text "my first name" is stored in the Henrik variable. - In the second line, the Henrik variable is stored in the myname variable. - Finally in line 3, the myname variable is written to the document. The result is that "my first name" will be written on the page.

ASSIGNING VALUES TO VARIABLES


The most common way to assign a value to a variable is using the equals sign. Consider these examples to see the different ways variables can be assigned to
contain either values or text. Note in particular how parentheses can be used to control how complex formulas are handled.
Example
a=2; a=2; a=2; a=2; a=2; a++; a--; b=3; c=a+b; d=a+6;

Resulting value a=2 a=3 a=1 c=5 d=8 (2+1) (2-1) (2+3) (2+6)

First="Henrik"; Last="Petersen"; Full=First+" "+Last; a=2*7; b=20/5; c=(20/5)*2; d=20/(5*2);

First=Henrik Last=Petersen Full=Henrik Petersen a=14 (2*7) b=4 (20/5) c=8 (4*2) d=2 (20/10)

ARITHMETHIC OPERATORS
The above table includes the so-called "arithmethic operators" a++ and a--. You could really live well without these, since what they do can be achieved by
using the other operators available.

However you will often see them used in scripts, and you might even be lazy
enough to use them yourself, since it is faster to type a++; than it is to typea=a+1;.

Operator
++

Explanation increment

Example a=5; a++; a would now equal 6 a=5; a--; a would now equal 4 a=8 % 3; a would now equal 2, since 8 can be divided by 3 two times leaving a remainder of 2.

--

decrement

returns modulus, which is what is left when two numbers are divided.

COMPARING VARIABLES
There are several different ways to compare variables. The simplest is comparing for equality, which is done using a double equals sign:
if (a==b) {alert("a equals b")};

if (lastname=="Petersen") {alert("Nice name!!!")};


Note: The if statement is explained in the next section.

If you forget to use double equals signs when comparing variables for equality,
and use a single equals sign instead, you will not compare the variables. What will happen is that the variable on the left side of the equals sign will be assigned the value of the variable to the right.

An example of the error:


if (lastname="Petersen") {alert("Nice name!!!")};

This is a very common bug that will totally ruin the script.

This table contains the different comparing operators:


Operator
==

Explanation equal to

Example 4==5 (false)

5==5 (true)
5==4 (false)

4!=5 (true)
!=

not equal to

5!=5 (false)

<

5!=4 (true) 4<5 (true)


less than 5<5 (false) 5<4 (false) 4>5 (false) 5>5 (false)

>

greater than

<=

less than or equal to

5>4 (true) 4<=5 (true) 5<=5 (true)


5<=4 (false) 4>=5 (false)

>=

greater than or equal to

5>=5 (true) 5>=4 (true)

On the function page you will learn more about global and local variables.

On the array page you will learn more about ways to work with large amounts of
variables.

IF AND ELSE
possibilities.

- Printable Version - Send Page To Frien

Sometimes javascript requires the ability to make distinctions between different For example, you might have a script that checks which browser the user arrives
with. If it's MSIE, a page specifically designed for that browser should be loaded, if it's Netscape another page should be loaded.

The general syntax for if statements is:

if (condition) {action1} else {action2};


An example could be:
if (browser=="MSIE") {alert("You are using MSIE")} else {alert("You are using Netscape")};

Again it is important to note that if is written as "if".


Using the capital "IF" would cause an error.

Also note that when comparing variables you will need to have two equals signs
next to each other (==).

If we wrote browser="MSIE" we would actually store "MSIE" in the variable


called browser.

When you write browser=="MSIE" javascript knows that you want it to


compare rather than assign a value.

The next section explains the different operators (=, <, > etc.).

More complex if statements can be made by simply entering new if statements in


the else part:

if (condition) {action1} else {if (condition) {action2} else {action3};};

An example:
if (browser=="MSIE") {alert("You are using MSIE")} else {if (browser=="Netscape") {alert("You are using Netscape")} else {alert("You are using an unknown browser")};};

AND, OR & NOT


To further enhance your if statements you can use the so-called logical operators. And is written as && and is used when you want to check if more than one
condition is true.

Ex: If the basket contains egg and the basket contains bacon, we can have egg
and bacon.

The syntax is: if (condition && condition) {action}


if (hour==12 && minute==0) {alert("it's noon")};

Or is written as || and is used when more than a one condition should result in the
check being true. (|| is achieved by using the shift key combined with the \ key)

Ex: If the basket contains milk or the basket contains water, we can have
something to drink.

The syntax is: if (condition || condition) {action}


if (hour==11 || hour==10) {alert("it's less than 2 hours till noon")};

Not is written as ! and is used to invert the result.


Ex: If not the basket contains egg or not the basket contains bacon, we cant
have egg and bacon.

The syntax is: if (!(condition)) {action}


if (!(hour==11)) {alert("it's more than 1 hour till noon")};

FUNCTIONS
the tasks as soon as the script is read, you might want your javascript to be performed only upon the detection of a certain event.

- Printable Version - Send Page To Frien

Instead of just adding your javascript to the page and having the browser perform For example, if you made a javascript code that changed the background color of
the page when the user clicked a button, then you would need to tell the browser, that the script should not be performed right away when loaded.

To keep the browser from performing a script as soon as it is loaded you need to
write the script as a function.

Javascript written into functions will not be performed until you specifically ask for
it. This way you gain complete control of the timing.

Look at this example of script lines written as a function:


<html> <head> <script> function myfunction() { alert("Welcome to my world!!"); } </script> </head> <body> <form name="myform"> <input type="button" value="Hit me" onclick="myfunction()"> </form> </body> </html>

Click the button to see what the script in the example does:

If the line: alert("Welcome to my world!!"); had not been written within a


function, it would simply be performed as soon as the line was loaded.

But since we wrote it as a function, it was not performed until you hit the button.

The call of the function is in this line:


<input type="button" value="Click Here" onclick="myfunction()">

As you can see, we placed the button in a form and added the
eventonClick="myfunction()" to the properties of the button.

The next page gives a detailed description of the different events you could use to
trigger functions.

The general syntax for a function is:

function functionname(variable1, variable2,..., variableX)


{
// Here goes the javascript lines for the function

The { and the } marks the start and end of the function.

A typical bug when entering javascript functions is to forget about the importance
of capitals in javascript. The word function must be spelled exactly

as function.Function or FUNCTION would cause an error.

Furthermore, use of capitals matters in the name of the function as well. If you had
a function called myfunction() it would cause an error if you referred to it asMyfunction(), MYFUNCTION() or MyFunction().

EVENTS
Events are actions that can be detected by javascript.

- Printable Version - Send Page To Frien

An example would be the onmouseover event, which is detected when the user
moves the mouse over an object.

Another event is the onload event, which is detected as soon as the page is
finished loading.

Usually, events are used in combination with functions, so that the function does
not start until the event happens.

An example would be a function that would animate a button. The function simply shifts two images. One image that shows the button in an "up"
position, and another image that shows the button in a "down" position.

If this function is called using an onmouseover event, it will make it look as if the
button is pressed down when the mouse is moved over the image.

The following are the most important events recognized by javascript:


Event
onfocus="" onblur="" onchange="" onselect="" onmouseover="" onmouseout="" onclick="" onload="" onunload="" onSubmit=""

Detected when Form field gets focus Form field looses focus Content of a field changes Text is selected Mouse moves over a link Mouse moves out of a link Mouse clicks an object Page is finished loading Browser opens new document Submit button is clicked

HTML tags select, text, textarea select, text, textarea select, text, textarea text, textarea A A A, button, checkbox, radio, reset, submit body, frameset body, frameset form

Events are used for two main purposes:

To perform a function upon detection of the event,

To show a popup box upon detection of the event.

Below is a brief description of the main purposes for each event.

onFocus, onblur and onchange are mainly used in combination with validation of
form fields.

Lets say you had a function called validateEmail() that would check to see if an
entered email address has an @ in it, and if it has a meaningful end, such as "com", "net" or whatever. Furthermore, suppose the user could enter his email address in a form.

You would then use the onchange event to call the function whenever the user
changes the content of the field:
<input type="text" size="20" onchange="validateEmail()">;

Click here to learn more about forms.


Click here to learn more about form field validation.

onload and onunload are mainly used for popups that appear when the user
enters or leaves the page. Another important use is in combination with cookies that should be set upon arrival or leaving your pages.

For example, you might have a popup asking the user to enter his name upon his
first arrival to your page. The name is then stored in a cookie. Furthermore, when the visitor leaves your page a cookie stores the current date. Next time the visitor arrives at your page, it will have another popup saying something like: "Welcome Bill Clinton, this page has not been updated since your last visit 8 days ago".

Click here to learn more about setting cookies.


Click here to learn more about popup boxes.

Another common use of the onLoad and onunload events is: Some annoying
pages have a function that immediately opens several other windows as soon as you enter the page. This is a clear break of netiquette, and is not considered proper webdesign.

onsubmit is used for one major purpose: To validate all fields within a form before
actually submitting it.

In the above example for onchange we showed how you can validate a single
form field.

Sometimes however, the visitor might find it annoying to have validations in the
middle of entering fields on a form. Rather than validating after each input, you might want the form to be validated only upon clicking the submit button.

This can be done using the onsubmit event. Assume you made a function named checkform() that would validate entries to a
form.

Now you want this function to be called when the user clicks the submit button.
If the content is not accepted by your function the submit should be cancelled. This way nothing would be submitted unless your function accepted the content.

What you should do, is: add an onsubmit event to the <form> tag this way:
<form method="yourchoice" action="yourchoice" onsubmit="return checkform()">

The function checkform() returns either true or false.


If it returns true the submit will take place. If it returns false the submit will be cancelled.

Click here to learn more about forms.


Click here to learn more about form validation.

onmouseover and onmouseout are mainly used for one purpose: To create
animated buttons.

You may have noticed that these events can only be used in combination with the
link tag <a>.

However, the events are often more useful in combination with the image
tag<img>. The trick to making the event work on an image is simply to turn the image into a link. (If the image is not supposed to actually work as a link, you could always make it link to an empty anchor, as shown in the example below).

Example: an alert box appears when an onmouseover is detected on an image:

The HTML from the example:


<a href="#" onmouseover="alert('I detected an onmouseover event'); return false" onmouseout="alert('I detected an onmouseout event'); return false"> <img src="rainbow.gif" width="60" height="60"> </a>

Note: The href="#" links the image to nowhere. If you really wanted the image to
link to a page you should enter the address of the page here instead.

Click here to learn more about links and anchors.


Click here to learn more about alert boxes.

LOOPS
50 times in a row.

- Printable Version - Send Page To Frien

Imagine that you wanted a script to perform the same routine over and over again An example could be if you wanted a script to produce a table comparing
temperatures in Fahrenheit and Celsius. The script should produce 50 lines in a table showing different temperatures according to the two scales.

Instead of adding 50 almost equal lines in your script you could use loops to make

the script perform a task like this.

There are two different kinds of loops: for and while. The for loop is used when you know in advance how many times the script should
perform. For example if you wanted it to create exactly 50 lines.

The while loop is used when you want the loop to continue until a certain
condition becomes true. For example, if you wanted to make a table comparing Celsius and Fahrenheit, stepping 15 degrees for each row, and you wanted the table to contain values up to 1200 degrees of Celsius.

Below is a description of each of these two loops:

FOR LOOPS:
SYNTAX:
for (variable=startvalue; variable<=endvalue;variable=variable+incrementfactor) {
// Here goes the script lines you want to loop.

Enter a variablename where it says variable.


Enter the startvalue of the loop where it says startvalue. Enter the endvalue of the loop where it says endvalue. Enter the factor each loop should increment where it says incrementfactor.

Note: The incrementfactor could be negative if you wanted.


Furthermore the <= could be any comparing statement, ex. >, == or whatever.

EXAMPLE:
<html> <head> <title>Celsius-Fahrenheit Converter</title> </head>

<body> <table border=3> <tr><td>CELSIUS</td><td>FAHRENHEIT</td></tr> <script language="javascript"> for (celsius=0; celsius<=50; celsius=celsius+1) { document.write("<tr><td>"+celsius+"</td><td>" +((celsius*9/5)+32)+"</td></tr>"); } </script> </table> </body> </html>

Click here to see the page from this example.

WHILE LOOPS:
SYNTAX:
while (variable<=endvalue) {
// Here goes the script lines you want to loop.

Enter a variablename where it says variable.


Enter the endvalue of the loop where it says endvalue.

Note: The <= could be anything that would fit the purpose ex. >, == or
whatever.

EXAMPLE:
<html> <head> <title>Celsius-Fahrenheit converter</title> </head> <body> <table border=3> <tr><td>CELSIUS</td><td>FAHRENHEIT</td></tr> <script language="javascript"> celsius=0; while (celsius<=50) { document.write("<tr><td>"+celsius+ "</td><td>"+((celsius*9/5)+32)+"</td></tr>"); celsius=celsius+1;

} </script> </table> </body> </html>

Click here to see the page from this example.

BREAK & CONTINUE


Two special commands can be used in loops: break and continue.

break simply breaks the loop and continues with what might follow after the loop.
An example would be if you had a loop calculate the squareroot of numbers
decrementing from 50.

Since calculating the square root of a negative number is an illegal mathemathic


operation you would like the loop to end when the square root of zero had been calculated.

To do this you would add this inside your loop:


if (value==0) {break};

continue breaks the current loop and continues with the next value.
An example would be if you had a loop that divided a certain value with a factor of
numbers ranging from -50 to +50.

Since division by zero is an illegal mathemathic procedure the loop would look like
this:
for (value=-50; value<=50; value=value+1) { if (value==0) {continue}; document.write((100/value)+"<br>");

ARRAYS
would have many more or less similar variables.

- Printable Version - Send Page To Frien

When working with more complex scripts you might face a situation in which you Instead of being forced to write a line for each operation
done to such a variable, you can use arrays to help you automate the process.

Consider this example:


Example 1
value1=10; value2=20; value3=30; .... here would go 96 similar lines .... value100=1000

Example 2

value=new Array; for (number=1; number<=100; number=number+1) { value[number]=number*10};

In example 1 you would need to enter 100 lines to perform an operation on your
variables.

In example 2 you only need to enter 3 lines no matter how many variables you
have.

An array must be defined before referring to any of the


variables in it.

This is done using the syntax: variablename=new Array; Replace variblename with the desired name of your array.
Note: new must be written in small letters and Array must start with a capital A.

As the example indicated, arrays become extremely powerful when used in


combination with loops.

However, you don't have to handle array variables in loops. Single variables can be addressed with a syntax like this:
value[9]=170;

Congratulations!
You have reached the end of the tutorial! When you feel comfortable with the basic javascript explained
in this section you should continue by learning about the javascript objects.

Objects are predefined functions for maths, text variables, browser controlling, etc. As a matter of fact each and every item placed on a webpage is an object that can
be changed, read, or written to by javascript.

This is where the real fun starts with javascript: When you start controlling the
single objects (form fields, buttons, images, menus, etc. etc.) on the pages.

That is where you really start taking your pages beyond


the average.

You can click here to explore the power of the javascript


built-in objects.

JAVASCRIPT TUTORIAL
webpages.

- Printable Version - Send Page To Frien

JavaScript is a scripting language that will allow you to add real programming to your You can use this tutorial either as a complete introduction or as an A-Z reference to
JavaScript.

The pages are packed with:


Easy to understand explanations, massive examples, tips, smart workarounds and useful quick references.

If you're completely new to JavaScript you should start with the section that covers
JavaScript Basics.

Otherwise, just jump directly to the relevant pages.


JAVASCRIPT BASICS
INTRODUCTION WHERE TO PLACE IT THE FIRST SCRIPT CAPITAL LETTERS POPUP BOXES VARIABLES IF AND ELSE FUNCTIONS EVENTS LOOPS ARRAYS TAKE THE QUIZ!

BROWSER DETECTION
INTRODUCTION TECHNIQUE THE CODE EXAMPLE DETECT TOOL

FORM VALIDATION
INTRODUCTION TECHNIQUE THE CODE EXAMPLE

MULTIPLE LINK
INTRODUCTION

ANIMATED BUTTONS
INTRODUCTION TECHNIQUE THE CODE EXAMPLE TECHNIQUE THE CODE EXAMPLE

FRAMESET SCRIPT
INTRODUCTION

COOKIES
INTRODUCTION TECHNIQUE THE CODE EXAMPLE TECHNIQUE THE CODE EXAMPLE

POPUP WINDOWS
INTRODUCTION

DROP DOWN MENU


INTRODUCTION TECHNIQUE THE CODE EXAMPLE TECHNIQUE THE CODE EXAMPLE POPUP TOOL

DROP DOWN TOOL

Browser Detection :

THE TECHNIQUE
Browser detection is based on the navigator object.
This object holds name, version, etc. of the browser.

- Printable Version - Send Page To Frien

Therefore it is pretty simple to write a script that will read these variables and
return the name and version of the current browser.

All you really need to do is use the indexOf function to find the version number.
This tutorial will teach you how.

THE CODE
First create a page with the standard skeleton code for all webpages:

- Printable Version - Send Page To Frien

BROWSER DETECTION SCRIPT - Step 1/3


<html> <head> <title>Browserdetection</Title> </head> <body> </body> </html>

The javascript that will detect the browser makes use of the navigator object. This object holds these interesting variables:
VARIABLES
navigator.appCodeName navigator.appName navigator.appVersion navigator.userAgent navigator.platform

DESCRIPTION The code name of the browser (e.g. Mozilla) The name of the browser (e.g. Netscape or Microsoft Internet Explorer) The browser version (e.g. 3.0 or 4.0) The header information for the browser. (e.g. Mozilla/4.0) The users operating system (e.g. WIN32)

The following information was derived from your browser when you arrived on this
page:

navigator.appCodeName navigator.appName navigator.appVersion navigator.userAgent navigator.platform

In short, all we need to do is have the webpage run our script once it's loaded. This is done by simply writing the javascript code without function declarations. The following lines should be added to the <head> section of the document:

BROWSER DETECTION SCRIPT - Step 2/3


<html> <head> <title>Browser detection</Title> <Script Language="JavaScript"> browsername=navigator.appName; if (browsername.indexOf("Netscape")!=-1) {browsername="NS"} else {if (browsername.indexOf("Microsoft")!=-1) {browsername="MSIE"} else {browsername="N/A"}}; </script> </head> <body> </body> </html>

The above lines store the name of the browser in the variable called
browsername.

If the browser is Microsoft Internet Explorer, "MSIE" is stored in the variable. If it is a Netscape browser, "NS" is stored in the variable.

If it's none of the above, "N/A" is stored in the variable.


Note - The use of indexOf() in the above script:

In the above script you can see this line:


if (browsername.indexOf("Microsoft")!=-1) {browsername="MSIE"}

The function browsername.indexOf("Microsoft") checks the


variablebrowsername for the first appearance of the word Microsoft.

If Microsoft is not present, the result will be -1.


So if browsername.indexOf("Microsoft") does not equal -1 ( != -1 ) it means that the word Microsoft is present somewhere in the browsername variable - and thus, the current browser is Microsoft Internet Explorer.

Now we need to find the version of the relevant browser. Since navigator.appVersion does not simply hold a value, like 2, 3 or 4, but rather
would hold a text, like "3.0b4Gold (Win95; I)", we need to make a little check of the text before we can save a more convenient value in the variable called browserversion.
browserversion="0"; if (navigator.appVersion.indexOf("2.")!=-1) if (navigator.appVersion.indexOf("3.")!=-1) if (navigator.appVersion.indexOf("4.")!=-1) if (navigator.appVersion.indexOf("5.")!=-1) if (navigator.appVersion.indexOf("6.")!=-1)

{browserversion="2"}; {browserversion="3"}; {browserversion="4"}; {browserversion="5"}; {browserversion="6"};

First we assign the value zero to the variable.


If none of the checks results in assigning a value to the variable, it will still hold the zero value after the checks. A value of zero thus means that the browserversion was not available.

The next 3 lines look for version numbers 2., 3., 4. and 5.
If navigator.appVersion contains any of the numbers, the value is stored in the variable called "browserversion".

The complete script now looks like this:

BROWSER DETECTION SCRIPT - Step 3/3

<html> <head> <title>Browser detection</Title> <Script Language="JavaScript"> browsername=navigator.appName; if (browsername.indexOf("Netscape")!=-1) {browsername="NS"} else {if (browsername.indexOf("Microsoft")!=-1) {browsername="MSIE"} else {browsername="N/A"}}; browserversion="0"; if (navigator.appVersion.indexOf("2.")!=-1) {browserversion="2"}; if (navigator.appVersion.indexOf("3.")!=-1) {browserversion="3"}; if (navigator.appVersion.indexOf("4.")!=-1) {browserversion="4"}; if (navigator.appVersion.indexOf("5.")!=-1) {browserversion="5"}; if (navigator.appVersion.indexOf("6.")!=-1) {browserversion="6"}; </script> </head> <body> </body> </html>

Now the script holds two variables: browsername and browserversion. This
information can be used for whatever purpose we choose.

The browser detection itself does nothing. All it does is - detect the visitors
browser. We still haven't added if-statements that tells the browser what it should do in the different cases.

In the example on the next page you will see how you can add if-statements to
the browser detection script - in order to send visitors to relevant pages.

EXAMPLE
to either Hotbot or MSN depending on the browser version. If it's none of the above the visitor is sent to Webcrawler.

- Printable Version - Send Page To Frien

In this example we send Netscape visitors to Yahoo, while we send MSIE visitors

BROWSER DETECTION SCRIPT


- with if statements
<html> <head> <title>Browser detection</Title> <Script Language="JavaScript"> // Browserdetectionscript made by Henrik Petersen / NetKontoret // Script explained at www.echoecho.com/javascript.htm // Please do not remove this and the two lines above. // Detect the browsername

browsername=navigator.appName; if (browsername.indexOf("Netscape")!=-1) {browsername="NS"} else {if (browsername.indexOf("Microsoft")!=-1) {browsername="MSIE"} else {browsername="N/A"}}; //detect the browserversion browserversion="0"; if (navigator.appVersion.indexOf("2.")!=-1) if (navigator.appVersion.indexOf("3.")!=-1) if (navigator.appVersion.indexOf("4.")!=-1) if (navigator.appVersion.indexOf("5.")!=-1) if (navigator.appVersion.indexOf("6.")!=-1)

{browserversion="2"}; {browserversion="3"}; {browserversion="4"}; {browserversion="5"}; {browserversion="6"};

// Send visitor to relevant pages if (browsername=="NS") {window.location="http://www.yahoo.com"}; if (browsername=="MSIE"){ if (browserversion<4){window.location="http://www.hotbot.com"} else {window.location="http://www.msn.com"} } if (browsername=="N/A") {window.location="http://www.webcrawler.com"}; </script> </head> <body> </body> </html>

Copy the code from this example to create your own browser detection page. Customize it by adding your own if statements and URLs at the bottom of the
script.

JAVASCRIPT TUTORIAL
webpages.

- Printable Version - Send Page To Frien

JavaScript is a scripting language that will allow you to add real programming to your You can use this tutorial either as a complete introduction or as an A-Z reference to
JavaScript.

The pages are packed with:


Easy to understand explanations, massive examples, tips, smart workarounds and useful quick references.

If you're completely new to JavaScript you should start with the section that covers
JavaScript Basics.

Otherwise, just jump directly to the relevant pages.

JAVASCRIPT BASICS
INTRODUCTION WHERE TO PLACE IT THE FIRST SCRIPT CAPITAL LETTERS POPUP BOXES VARIABLES IF AND ELSE FUNCTIONS EVENTS LOOPS ARRAYS TAKE THE QUIZ!

BROWSER DETECTION
INTRODUCTION TECHNIQUE THE CODE EXAMPLE DETECT TOOL

FORM VALIDATION
INTRODUCTION TECHNIQUE THE CODE EXAMPLE

MULTIPLE LINK
INTRODUCTION

ANIMATED BUTTONS
INTRODUCTION TECHNIQUE THE CODE EXAMPLE TECHNIQUE THE CODE EXAMPLE

FRAMESET SCRIPT
INTRODUCTION

COOKIES
INTRODUCTION TECHNIQUE THE CODE EXAMPLE TECHNIQUE THE CODE EXAMPLE

POPUP WINDOWS
INTRODUCTION

DROP DOWN MENU


INTRODUCTION TECHNIQUE THE CODE EXAMPLE DROP DOWN TOOL TECHNIQUE THE CODE EXAMPLE POPUP TOOL

Advanced Scripts :

ANIMATED BUTTONS

- Printable Version - Send Page To Frien

Below is an example of a button that is animated using javascript technique. Try moving the mouse over the button.

The same effect could be achieved with Java Applets. The rest of this article will teach you how to create the effect with javascript.

Animated Buttons :

THE TECHNIQUE
webpage.

- Printable Version - Send Page To Frien

We place the button on the page as we would have placed any other image on a Then we add an onMouseOver event to the image.
The event causes the browser to run a javascript function that will replace the initial image with another image.

Finally we add an onMouseOut event to the image as well.


This event causes the browser to run a javascript function that inserts the initial image again when the user moves the mouse away from the image.

The technique is thus a two step process: First, you need to add mouse event settings to the HTML tags of the images. Second, you need to add a script that will be performed when the browser detects
the mouse events.

<< PREVIOUS

READ MORE >>

Animated Buttons :

THE CODE

- Printable Version - Send Page To Frien

Before you can add an animated button to your page you need to add the button
image itself.

After adding the button image to the webpage you need to add a few comments to
the image tag.

After that you can add the javascript that changes the image when the mouse
moves over it.

The first half of this page covers the plain HTML code for inserting an image so
that javascript can refer to it.

The second half covers the javascript that changes the image when a mouseover
occurs.

THE HTML CODE


A regular image that works as a link button looks somewhat like this in HTML
code:
<a href="mypage.htm"> <Img Src="button1a.gif"> </a>

To make it possible for javascript to change the image we need to give it a name
that can be used by javascript to address it.

So in our case the HTML would look like this:


<a href="mypage.htm"> <Img Src="button1a.gif" name="button1"> </a>

Now the button has a name that can be used as a reference when we want
javascript to replace it with another image.

We need to tell the browser that once a mouse is rolled over the image, the
browser should execute a function that replaces the image. This is done with the onMouseOver event.

In addition we also need to tell the browser that once the user rolls the mouse
away from the image, another javascript should be solved in order to let the initial image of the button return. This is done with the onMouseOut event.

The final HTML code looks like this:


<a href="mypage.htm" onmouseOver="MouseOverRoutine('button1')" onmouseOut="MouseOutRoutine('button1')"> <Img Src="button1a.gif" name="button1" ></a>

This is all you need to do in the HTML part of the page. The rest is done in
javascript.

Note:
The mouse events are added to the <a href> tag - NOT the image tag. This is because browsers do not look for mouseover events on images. As stupid as it may sound it is nevertheless true. Therefore we can only make images animated by turning them into links. Since browsers understand mouseover events on links, they will register a mouse event on an image, if that image is a link.

THE JAVASCRIPT CODE


The following javascript should be added to the head part of your webpage.
<Script> <!-// The previous line hides the script from // old browsers that can't interpret it // // // // Assuming the image of the up button is called "button1a.gif" And that the image of the down button is called "button1b.gif" We can now read these two images into variables called button1up and button1down.

button1up = new Image; button1up.src = "button1a.gif"; button1down = new Image; button1down.src = "button1b.gif"; // Now the two images are defined. // Next step is the two functions needed. // The first function is called MouseOverRoutine, // and causes button1up to shift to button1down. function MouseOverRoutine(ButtonName) { if (ButtonName=="button1") {document.button1.src = button1down.src;}

} // Now our button will shift from button1up to button1down // when a mouseover event occurs. // To complete the script all we need to do // is make the inverse function, that will do exactly the opposite // when a mouseout event occurs. function MouseOutRoutine(ButtonName) { if (ButtonName=="button1") {document.button1.src = button1up.src;} } // Thats all there is. // The final step is ending the script section which is done by two lines: // The next line causes oldfashion browsers to // start interpreting the code again. //--> </script>

If you want more than one button on your page, all you need to do is double each
line referring to button1 and change it to button2, button3 or whatever number of buttons you might have.

Advanced Scripts :

COOKIES
user's computer.

- Printable Version - Send Page To Frien

A cookie is simply a variable that your webpage can store on or retrieve from the The idea is that the next time the user arrives at your page, the value of the cookie
can be read by your page, and then used for whatever purpose you choose.

Examples of cookies could be:

First time the visitor arrives the name is entered. (for example "John Wayne"). The username is then stored in a cookie. Next time he arrives at your page, it writes something like: "Welcome to my page John Wayne!! Good to see you again". The name is simply retrieved from the stored cookie.

First time the user arrives at your page she enters the desired language. The chosen language is stored in a cookie.

Next time she visits your site, she will simply be taken to the pages in the desired language without asking, since the desired language is retrieved from the cookie.

First time the user arrives at your page he is asked to fill in a password. The password is saved in a cookie. Next time he arrives at your page, the password is retrieved from the cookie.

Cookies :

THE TECHNIQUE
Cookies can be stored and retrieved using javascript. The script first checks to see if a cookie has already been set.

- Printable Version - Send Page To Frien

If so, it uses the cookie for some purpose.

If not, it sets a cookie and uses it the next time the user arrives at the page.

Cookies are stored until a specified expiration date. If a cookie is present when a user arrives at your page it is stored in
thedocument.cookie object.

This article will teach you how to read the cookie from
the document.cookieobject, as well as how to specify the variables used in the setCookie command.

THE CODE
In order to use cookies on a page you need:

- Printable Version - Send Page To Frien

a function that reads the cookie (if present)

a function that stores the cookie

a function that deletes the cookie

Below are three functions that perform these tasks:

getCookie

setCookie

delCookie

function getCookie(NameOfCookie) { // First we check to see if there is a cookie stored. // Otherwise the length of document.cookie would be zero. if (document.cookie.length > 0) { // Second we check to see if the cookie's name is stored in the // "document.cookie" object for the page. // // // // // // Since more than one cookie can be set on a single page it is possible that our cookie is not present, even though the "document.cookie" object is not just an empty text. If our cookie name is not present the value -1 is stored in the variable called "begin".

begin = document.cookie.indexOf(NameOfCookie+"="); if (begin != -1) // Note: != means "is not equal to" { // Our cookie was set. // The value stored in the cookie is returned from the function. begin += NameOfCookie.length+1; end = document.cookie.indexOf(";", begin); if (end == -1) end = document.cookie.length; return unescape(document.cookie.substring(begin, end)); } } return null; // Our cookie was not set. // The value "null" is returned from the function. }

function setCookie(NameOfCookie, value, expiredays) { // // // // // Three variables are used to set the new cookie. The name of the cookie, the value to be stored, and finally the number of days until the cookie expires. The first lines in the function convert the number of days to a valid date.

var ExpireDate = new Date (); ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000)); // // // // The next line stores the cookie, simply by assigning the values to the "document.cookie" object. Note the date is converted to Greenwich Mean time using the "toGMTstring()" function.

document.cookie = NameOfCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString()); }

function delCookie (NameOfCookie) { // The function simply checks to see if the cookie is set. // If so, the expiration date is set to Jan. 1st 1970. if (getCookie(NameOfCookie)) { document.cookie = NameOfCookie + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; } }

MAKING IT WORK
Simply adding the above code to a page does not set any cookies. The functions
are the tools you need in order to read, set, and delete cookies on your page.

The final step in adding a cookie to your page is to add a purpose to the cookie.
Decide whether you want the cookie to store the user's name, the date of his last visit to your page or the preferred language. Or use the cookie for whatever purpose you wish.

In any case, the codes you need to add to the cookie scripts will be different.

RAW SCRIPT
Below is the cookie script without the comments. Copy and paste to use the script
on your own site.
function getCookie(NameOfCookie) { if (document.cookie.length > 0) { begin = document.cookie.indexOf(NameOfCookie+"="); if (begin != -1) { begin += NameOfCookie.length+1; end = document.cookie.indexOf(";", begin); if (end == -1) end = document.cookie.length; return unescape(document.cookie.substring(begin, end)); } } return null; }

function setCookie(NameOfCookie, value, expiredays) { var ExpireDate = new Date (); ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000)); document.cookie = NameOfCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString()); }

function delCookie (NameOfCookie) { if (getCookie(NameOfCookie)) { document.cookie = NameOfCookie + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; } }

Cookies :

EXAMPLE
name.

- Printable Version - Send Page To Frien

Click here to see a sample page showing how to make the cookie store the user's Click here to see a sample page showing how to make the cookie store the date
of user's last visit.

Click here to see an extended version of the above cookie script:

it detects if the site has been updated since the user's last visit.

If so, a confirm box gives the option to go to an update page to see what's new.

Click here to see a sample page showing how to make the cookie store a user
preference.

Click here to see a sample page showing how to make the cookie launch a
window the first time a visitor arrives - but not the following times.

Click here to see a sample page showing how to make the cookie count the
number of visits, and launch a window the first 3 times a visitor arrives - but not the following times.

DROP-DOWN MENU
Consider these menu buttons
(Note: the menus are not activated on this page):
SEARCH ENGINES THIS SITE

- Printable Version - Send Page To Frien

When you choose an option from one of them, you will be taken to the referring
page.

If you have many links on a single page it can be very useful to bundle the links
into drop-down menus rather than covering the entire page with links.

The script that makes the drop-down menus work as links is very simple, yet,
extremely powerful.

It works with framesets also, giving you the option to open links in new windows. Furthermore, you can add as many drop-down menus as you'd like to the script. It
is not necessary to add a new script each time you include a new menu.

If you're not particulary interested in the javascript itself, but would rather just have
a menu on your page, click the link to go to the Drop-Down Menu Tool

Drop-Down Menu :

THE TECHNIQUE

- Printable Version - Send Page To Frien

Each field in the drop-down menu has a name that will show in the menu. The value attached to each of the fields are the URLs that should be called when
the option is selected.

By adding onChange="DropDownMenu(this)" to the <select> tags we force the


browser to run our script when a field is picked from a menu. The script then reads which option is picked, and loads the referring page.

It is possible to add a target to the URL which means that the referring page can
either be loaded into the same window, into a specific frame, or into a new window.

Drop-Down Menu :

THE CODE
your document.

- Printable Version - Send Page To Frien

To make this script work on your page you need to add it to the <head> section of Next you need to add onChange="DropDownMenu(this)" to each drop-down
menu that should call the script.

The onChange is added to the <select> tag of the desired


drop-down menu.

Finally you need to add the desired URL and the optional target to each of the
options in the menus.

To do this use the following syntax:


<option value="http://www.yahoo.com">Yahoo</option>

If you want to add a target to the link use this syntax:


<option value="http://www.yahoo.com&target">Yahoo</option>

where "target" is replaced by the target you want to use.

If you wanted the link to open in a frame called "main" you would add:
<option value="http://www.yahoo.com&main">Yahoo</option>

Note:
You can also use the reserved targets:

"_blank"

"_top"

"_parent"

"_self"

Click here to get an explanation of these targets.

Finally, you can enter FALSE in the URL field to let the script know that the option
shouldn't load a page. This is what you do if you want one of the options to be a header for the drop-down menu - for example "SEARCH ENGINES" and "THIS SITE" in the two examples shown at the top of this page.

The script looks like this:


<script> function DropDownMenu(entered) { // ********************************* // DROP DOWN MENU (c) Henrik Petersen / NetKontoret 1998 - All rights reserved // Explained along with other useful scripts at: http://www.echoecho.com/javascript.htm // You may freely use this script as long as you do not remove this line and the 2 lines above. // ****************************************** with (entered) { // Store the selected option in a variable called ref ref=options[selectedIndex].value; // Count the position of the optional & splitcharacter=ref.lastIndexOf("&"); // The three lines below checks if a target goes along with the URL // That is: (if a "&" is in the option-value). // If so, the URL is stored in a variable called loc and the target // is stored in a variable called target. // If not the URL is stored in a variable called loc and "_self"

is // stored in the variable called target. if (splitcharacter!=-1) {loc=ref.substring(0,splitcharacter); target=ref.substring(splitcharacter+1,1000).toLowerCase();} else {loc=ref; target="_self";}; // create a varible called lowloc to store loc in lowercase characters. lowloc=loc.toLowerCase(); // Skip the rest of this function if the selected optionvalue is "false". if (lowloc=="false") {return;} // Open link in current document if (target=="_self") {document.location=loc;} // Cancel eventual framesets and open link in current window else {if (target=="_top") {top.location=loc;} // Open link in new window else {if (target=="_blank") {window.open(loc);} // Open link in parent frame else{if (target=="_parent") {parent.location=loc;} // Open link in the specified frame else {parent.frames[target].location=loc;}; }}}} } </script>

EXAMPLE
Click here to see a sample page using this script.

- Printable Version - Send Page To Frien

SCRIPT WITHOUT COMMENTS


If you'd prefer to copy the code without comments, you may copy the script entered
below:
<script> function DropDownMenu(entered) { // *************************************************************************** // DROP DOWN MENU (c) Henrik Petersen / NetKontoret 1998 - All rights reserved // Explained along with other useful scripts at: http://www.echoecho.com/javascript.htm // You may freely use this script as long as you do not remove this line and the 2 lines above. // *************************************************************************** with (entered)

{ ref=options[selectedIndex].value; splitcharacter=ref.lastIndexOf("&"); if (splitcharacter!=-1) {loc=ref.substring(0,splitcharacter); target=ref.substring(splitcharacter+1,1000).toLowerCase();} else {loc=ref; target="_self";}; lowloc=loc.toLowerCase(); if (lowloc=="false") {return;} if (target=="_self") {document.location=loc;} else {if (target=="_top") {top.location=loc;} else {if (target=="_blank") {window.open(loc);} else{if (target=="_parent") {parent.location=loc;} else {parent.frames[target].location=loc;}; }}}} } </script>

FORM VALIDATION
Javascript is a strong tool for validating forms before sending the content.
The most obvious things to check for are whether an emailaddress has valid syntax, or if fields meant for values have text entered, etc.

- Printable Version - Send Page To Frien

This page covers the 4 most important techniques. Consider this form:
EMAIL: VALUE (0-5): VALUE (Integer, 3-4 digits): Do not leave this field empty:
Click here to validate all fields at once

Note: The form is not activated - Try entering values to see what happens.

THE TECHNIQUE
The javascript to validate inputs to a form consists of four different functions:

- Printable Version - Send Page To Frien

emailvalidation will check to see if a value lives up to the general syntax of an email.

valuevalidation will check to see if a value is within a certain interval.

digitvalidation will check to see if a value consits of a certain number of digits.

emptyvalidation will check to see if a field is empty or not.

The validation can take place as the visitor enters values, or all at once upon
clicking the submit button after entering the values.

Each validation function can easily be customized to fit the needs of the fields they
are checking.

THE CODE
below:
emailvalidation(this,text)

- Printable Version - Send Page To Frien

The script explained on this page actually consists of the four functions listed

valuevalidation(this,min,max,text,type)

digitvalidation(this,min,max,text,type)

emptyvalidation(this,text)

You can either validate each field whenever it is changed or you can validate all
fields at one time when the submit button is clicked.

At the last half of this page you can learn how to use either of these methods
along with the scripts.

First, let's look at the different validation scripts.

emailvalidation(this,text) Checking if the content has the general syntax of an email. Optional parameters are: text--text that will show in an alertbox if content is illegal.
function emailvalidation(entered, alertbox) { // E-mail Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { apos=value.indexOf("@"); dotpos=value.lastIndexOf("."); lastpos=value.length-1; if (apos<1 || dotpos-apos<2 || lastpos-dotpos>3 || lastposdotpos<2) {if (alertbox) {alert(alertbox);} return false;} else {return true;} } }

valuevalidation(this,min,max,text,type) Checking if the content is a number in a limited area. Optional parameters are: min --minimum value allowed in the field.

max --maximum value allowed in the field. text --text that will show in an alertbox if content is illegal. type --enter "I" if only integers are allowed.
function valuevalidation(entered, min, max, alertbox, datatype) { // Value Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { checkvalue=parseFloat(value); if (datatype) {smalldatatype=datatype.toLowerCase(); if (smalldatatype.charAt(0)=="i") {checkvalue=parseInt(value)}; } if ((parseFloat(min)==min && checkvalue<min) || (parseFloat(max)==max && checkvalue>max) || value!=checkvalue) {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } }

digitvalidation(this,min,max,text,type) Checking if the content has a certain number of digits. Optional parameters are: min --minimum number of digits allowed in the field.

max --maximum number of digits allowed in the field. text --text that will show in an alertbox if content is illegal. type --enter "I" if only integers are allowed.
function digitvalidation(entered, min, max, alertbox, datatype) { // Digit Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { checkvalue=parseFloat(value); if (datatype) {smalldatatype=datatype.toLowerCase(); if (smalldatatype.charAt(0)=="i") {checkvalue=parseInt(value); if (value.indexOf(".")!=-1) {checkvalue=checkvalue+1}}; } if ((parseFloat(min)==min && value.length<min) || (parseFloat(max)==max && value.length>max) || value!=checkvalue) {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } }

emptyvalidation(this,text) Checking if the field is empty. Optional parameters are: text --text that will show in an alertbox if content is illegal.
function emptyvalidation(entered, alertbox) { // Emptyfield Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { if (value==null || value=="") {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } }

Note: All functions require this to be entered as a parameter. Simply enter the word "this" as a parameter when calling one of the functions. This will pass the content of the current field to the function.

If text is not entered when you call the function, it will not launch a popup box if an
error is detected. However, the function will still return the value "false". This option is used when we check for several possible errors at one time. That is:

when all fields are checked once the submit button is clicked.

USING THE VALIDATION SCRIPTS


There are two different ways to call these functions. One is used when you want to check the field immediately after an input is made to it. The other is when you want to check all fields at one time, when the user clicks the submit button.

onChange Validation:
To force the browser to check each field immediately, we add an onChange to each of the <input> tags in the form.

For example: if we wanted to check if the value of a certain text field had a valid e-mail address we
would add this:
<input type="text" name="Email" size="20" onChange="emailvalidation(this,'The E-mail is not valid');">

onSubmit Validation
You might prefer to check all fields at one time when the user hits the submit button. To do this you should add an onSubmit event handler to the <form>tag.

If, for example you have a form called "myform" and you want all fields checked when the user
clicks 'submit' you should create a function that checks all the fields.

This function should then be called by an onSubmit-event added to the <form>tag. If this function was called "formvalidation()" the <form> tag would look like this:
<form onsubmit="return formvalidation(this)">

The function that checks the entire form will either return a value of false or true. If it's true the form
will be submitted - if it's false the submission will be cancelled.

A script that checks all fields in a form could look like this:

function formvalidation(thisform) This function checks the entire form before it is submitted.
function formvalidation(thisform) { with (thisform) { if (emailvalidation(Email,"Illegal E-mail")==false) {Email.focus(); return false;}; if (valuevalidation(Value,0,5,"Value MUST be in the range 05")==false) {Value.focus(); return false;}; if (digitvalidation(Digits,3,4,"You MUST enter 3 or 4 integer digits","I")==false) {Digits.focus(); return false;}; if (emptyvalidation(Whatever,"The textfield is empty")==false) {Whatever.focus(); return false;}; } }

Note:
The above function works in addition to the four functions listed at the top of this page. Furthermore, the function needs to be customized to fit your form.

You will need to enter the appropriate form field names used on your own form. (Instead of "Email", "Value", "Digits" and "Whatever" in this example).

Furthermore you would need to call the appropriate functions depending on which check you
would like to perform on each form field.

(In the example each field is checked by a different function. You could as well have each field
checked by the same function. If for example the form had 4 fields that should all contain an email address you would add an emailvalidation to each. )

<< PREVIOUS

Form Validation :

EXAMPLE
Click here to see a sample page using this script.

- Printable Version - Send Page To Frien

THE ENTIRE SCRIPT


If you want to use all four validation scripts and the script that will check all fields at once, feel free to copy the entire code listed below to your page.

Note:
The function called formvalidation() needs to be customized to fit your own

form.
<script> function emailvalidation(entered, alertbox) { // E-mail Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { apos=value.indexOf("@"); dotpos=value.lastIndexOf("."); lastpos=value.length-1; if (apos<1 || dotpos-apos<2 || lastpos-dotpos>3 || lastposdotpos<2) {if (alertbox) {alert(alertbox);} return false;} else {return true;} } } function valuevalidation(entered, min, max, alertbox, datatype) { // Value Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { checkvalue=parseFloat(value); if (datatype) {smalldatatype=datatype.toLowerCase(); if (smalldatatype.charAt(0)=="i") {checkvalue=parseInt(value)}; } if ((parseFloat(min)==min && checkvalue<min) || (parseFloat(max)==max && checkvalue>max) || value!=checkvalue) {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } } function digitvalidation(entered, min, max, alertbox, datatype) { // Digit Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { checkvalue=parseFloat(value); if (datatype) {smalldatatype=datatype.toLowerCase(); if (smalldatatype.charAt(0)=="i") {checkvalue=parseInt(value); if (value.indexOf(".")!=-1) {checkvalue=checkvalue+1}}; } if ((parseFloat(min)==min && value.length<min) || (parseFloat(max)==max && value.length>max) || value!=checkvalue) {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } } function emptyvalidation(entered, alertbox) {

// Emptyfield Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { if (value==null || value=="") {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } } function formvalidation(thisform) { // This function checks the entire form before it is submitted // Note: This function needs to be customized to fit your form with (thisform) { if (emailvalidation(Email,"Illegal E-mail")==false) {Email.focus(); return false;}; if (valuevalidation(Value,0,5,"Value MUST be in the range 05")==false) {Value.focus(); return false;}; if (digitvalidation(Digits,3,4,"You MUST enter 3 or 4 integer digits","I")==false) {Digits.focus(); return false;}; if (emptyvalidation(Whatever,"The textfield is empty")==false) {Whatever.focus(); return false;}; } } </script>

Multiple Links :

THE TECHNIQUE
This script will let us open two or more pages when a single link is clicked.

- Printable Version - Send Page To Frien

First we neutralize the html link. This is done by letting the link point to "#" which
means it points to nowhere and thus has no effect in HTML.

The trick is, that at the same time, we add an onClick event to the link. This event
will, in return, execute our small javascript that opens the two pages.

In this article we will limit the script to open two pages.


But as we said, the technique can easily be used to open as many pages as you like from a single li

Multiple Links :

THE CODE
Assuming you want a link to open Yahoo in a frame called bannerframe and
AltaVista in a frame called mainframe the code looks like this:
<a href="#" onClick=" parent.bannerframe.location='http://www.Yahoo.com'; parent.mainframe.location='http://www.altavista.com';

- Printable Version - Send Page To Frien

return false; ">

As you can see, we simply add a:


parent.framename.location='linkname';

for each page we want to open. You can, of course, add as many links as you like.

NOTE:
The onClick event is enclosed by double quotes. The javascript links are enclosed by single quotes.

The return false statement makes sure that the browser doesn't even try to
interpret the html link (pointing to #). This is necessary because sometimes a link to an unexisting anchor forces the browser to go to the top of the page (which might not be what we want).

FRAMESET SCRIPT
Javascript can be a powerful addition to frames pages.

- Printable Version - Send Page To Frien

One of the biggest disadvantages of frame based websites has been that you
could not refer to your subpages, unless you wanted the visitor to open it oustside the frameset.

With javascript, you can create subpages that - if loaded outside the frameset will load themselves into the frameset.

That's what the rest of this article is about.

THE TECHNIQUE
This script ensures that subpages aren't loaded outside a frameset.

- Printable Version - Send Page To Frien

If a visitor enters the url of a subpage - the script will make sure that the frameset
is loaded with the subpage in one of the frames.

We will need to enter a small script on both the frameset page and each of the
subpages.

What actually happens is this: If a subpage is loaded outside the frameset, the script on the subpage will detect it
and load the frameset instead.

Once the frameset is loaded, the script on the frameset page will load the referring
subpage into the correct frame window.

THE CODE
your subpages and your frameset page.

- Printable Version - Send Page To Frien

As mentioned on the previous page, you need to enter a small script in the<head> section of both

THE CODE FOR THE SUB PAGES


The script to copy and paste to the <HEAD>-section of your subpages looks like this:
<HEAD> <script> function detect() { framesetpage="myframeset.htm"; thispage=window.location.href; if (thispage.indexOf('://')<0) {thispage="://"+thispage;}; prefix=thispage.substring(0,thispage.lastIndexOf('://')); suffix=thispage.substring(thispage.lastIndexOf('://')+3,thispage.length); // alert('the subpage is:['+prefix+']['+suffix+']'); if (parent.location.href==window.location.href) {parent.location.href=framesetpage+"?"+prefix+"&&&"+suffix}; } </script> </HEAD>

Customize this line to fit your own pages (replace myframeset.htm with the name of your own
frameset page.):
framesetpage="myframeset.htm";

In addition to adding the above script, you also need to add an onLoad-event to the <BODY>-tag.
<BODY onLoad="detect()">

That's it. After adding this piece of code to each of your subpages you're can proceed to the final
step: adding a code-piece to the frameset-page itself.

Before describing the code to add to the frameset-page, we will explain how the code for the
subpages works.

HOW IT WORKS
This line detects if the page is loaded into a frameset:
if (parent.location.href==window.location.href)

parent.location.href returns the url of the parent frame. window.location.href returns the url of the current page.

Now, if these two are the similar it means that there are no parent frames: the current page is the
top page.

In that case, this line is executed:


parent.location.href=framesetpage+"?"+prefix+"&&&"+suffix;

It opens the frameset page similar to if you had


enteredhttp://www.yourdomain.com/framespage.htm?http&&&www.yourdomain.com/subpage.htm in the url box of your browser.

The trick of this entire script is that the script on the framespage can access the entry that follows
the ? through the javascript built-in window.location.searchobject.

That is how the information is passed to tell the frameset page which subpage to load.

THE CODE FOR THE FRAMESET PAGE


This is the script to copy and paste to the frames page:
<HTML> <HEAD> <TITLE>MyFramesPage</TITLE>

<SCRIPT LANGUAGE="JavaScript"> <!-defaultsubpage="defaultsub.htm"; if (location.search) {subpage=location.search.substring(1)} else {subpage=defaultsubpage} if (subpage.indexOf('&&&')>=0) { prefix=subpage.substring(0,subpage.indexOf('&&&'))+"://"; suffix=subpage.substring(subpage.indexOf('&&&')+3,subpage.length); subpage=prefix+suffix; } // --> </SCRIPT> </HEAD>

<SCRIPT> document.write('<FRAMESET COLS="50%,50%">'); document.write('<FRAME SRC="navpage.htm" NAME="nav">'); document.write('<FRAME SRC="'+subpage+'" NAME="main">'); document.write('</FRAMESET>'); </SCRIPT> </HTML>

Customize the frameset values to fit your own page. You need to customize this one line:
defaultsubpage="defaultsub.htm";

Replace defaultsub.htm with the name of your own default page for the frameset.

Also note, that in this line:


document.write('<FRAME SRC="'+subpage+'" NAME="main">');

main is the name of the "intelligent" frame. You can pick any name you want for the frame, we just used the name main for our example.

HOW IT WORKS
These lines detects if a value was passed to the frameset page following a ? in the url:
if (location.search) {subpage=location.search.substring(1)}

else {subpage=defaultsubpage}

If a value was entered after a ? in the url, then the script returns the value. Otherwise it returns the
name you entered for the default page to load (in our example it would be "defaultsub.htm").

Now, if this page was called from a subpage that was loaded outside of the frameset, then the url
would look something like this:
http://www.yourdomain.com/framespage.htm?http&&&www.yourdomain.com/subpage.htm

For technical reasons the subpage doesn't pass the URL of the subpage as is. It uses &&& instead
of the normal :// that you usually see in a URL. (The reason is that netscape can't pass these values in a querystring).

This url based on &&& is translated into a real url by these lines at the top of our script:
if (subpage.indexOf('&&&')>=0) { prefix=subpage.substring(0,subpage.indexOf('&&&'))+"://"; suffix=subpage.substring(subpage.indexOf('&&&')+3,subpage.length); subpage=prefix+suffix; }

The final part of our script is the document.write lines that writes the HTML for the frameset.
document.write('<FRAMESET COLS="50%,50%">'); document.write('<FRAME SRC="navpage.htm" NAME="nav">'); document.write('<FRAME SRC="'+subpage+'" NAME="main">'); document.write('</FRAMESET>');

The variable subpage either contains the url of the default page or - if the frameset was launched by
a subpage - the url of the subpage to load into the "intelligent" frame.

EXAMPLE
To let you try out the scripts we produced a sample page. It consists of four files:

- Printable Version - Send Page To Frien

framespage.htm--The page that declares the frameset.

navpage.htm--The page that is loaded into the left frame window.

defaultsub.htm--The defaultpage to be loaded into the right frame


window.

subpage.htm--A secondary page that can be loaded into the right frame
window.

The most interesting page is subpage.htm.


Although it is not a default page declared in the frameset, it will be opened within the frameset if we try to open it.

When you click the links to the sample page, it will open in a new window. Just
close that window to return back here.

Click to open framespage.htm.


It will open the frameset in the ordinary way.

Click to open subpage.htm.


It will try to open subpage outside the frameset. As you will see, the script ensures that the page gets opened within the frameset instead.

POPUP WINDOWS
javascript to do so. Instead you should simply add the property target="_blank" in the <a href> tag:
<a href="http://www.yahoo.com" target="_blank">Go to Yahoo</a>

- Printable Version - Send Page To Frien

If you want a link to open a document in a new regular window you should not use

This technique is explained in the HTML section.

With javascript it is possible to open and close a new window in a much more
powerful way.

With javascript you can position and define the size of the pop up windows - so
they don't just pop up with a random size at a random position, like they do if you open a new window in plain HTML.

You will also learn to open windows where you decide which navigation buttons
etc. that should be available to the user (if any).

Proceed to get all the details!

THE TECHNIQUE
JavaScript has built-in methods for opening and closing windows.

- Printable Version - Send Page To Frien

The window.open method lets you open a new window in a much more powerful
way than if you had opened it with plain HTML using target="blank".

You can specify the size of the new window. Furthermore you can specify which browser buttons and menus etc. you want to
appear in the new window.

Finally you can even control the position of the new window.

THE CODE
When working with popup windows, three different techniques are relevant:

- Printable Version - Send Page To Frien

HOW TO OPEN A WINDOW

HOW TO CLOSE A WINDOW

HOW TO CUSTOMIZE A WINDOW

This page covers these techniques one by one.

OPEN WINDOW
The basic javascript to open a new window is:
MyNewWindow= window.open("http://www.mydomain.com/myfile.html", "NameOfMyWindow");

This will open a new window similar to the one described on the previous page. We still haven't set any conditions for the size of the window or which of the
browsers menus and buttons we want to be present.

CLOSE WINDOW
The javascript to close the window is:
NameOfMyWindow.close();

NameOfMyWindow is the name you assigned to the window when you opened it.
Note:
If you want to close the current active window you do not need to specify the window name.

Instead you can simply use:


window.close();

CUSTOMIZING A WINDOW
You can add several parameters for the new window. This will allow you to control the size as well as which parts of the browser should

be available in the window.


option
toolbar = yes | no location = yes | no directories = yes | no status = yes | no menubar = yes | no scrollbars = yes | no resizeable = yes | no width = value height = value

explanation add/remove browsers toolbar add/remove browsers location field add/remove browsers directories field add/remove browsers status field add/remove browsers menubar add/remove browsers scrollbars allow new window to be resizable window width in pixels window height in pixels

An example showing the way to define which parts of the browser should be
visible is shown below:
PageURL="http://www.mydomain.com/myfile.html"; WindowName="MyPopUpWindow"; settings= "toolbar=yes,location=yes,directories=yes,"+ "status=no,menubar=no,scrollbars=yes,"+ "resizable=yes,width=600,height=300"; MyNewWindow= window.open(PageURL,WindowName,settings);

Note: There are no spaces between the settings. If you add spaces here, the window will not open correctly in Netscape browsers.

Popup Windows :

EXAMPLE
pages.

- Printable Version - Send Page To Frien

This is a ready to use script that will allow you to easily open new windows on your You can customize the script using the information in the preceeding section. The script needs to be placed in the <head> section of your HTML document.
<script Language="JavaScript"> <!-function popup(url, name, width, height) { settings=

"toolbar=yes,location=yes,directories=yes,"+ "status=no,menubar=no,scrollbars=yes,"+ "resizable=yes,width="+width+",height="+height; MyNewWindow=window.open("http://"+url,name,settings); } //--> </script>

Once the script is added to your page, you can open windows using this syntax for
the link tags:
<a href="#" onClick="popup('www.yahoo.com', 'Win1', 300, 300); return false"> Click Here To Go to Yahoo</a>

Try the script by pressing the link below:


Click Here To Go to Yahoo

If you don't want to use the ready to use script in the previous section, click hereto
go to the Popup Windows Tool.

Note:
In the example, we named the window "MyWindow".If you have more than one popup window on the same page, you need to rename the window names. Use for example "MyWindow1", "MyWindow2" etc.

ARRAY OBJECT
Core Object
Array Multidimensional variable

- Printable Version - Send Page To Frien

NN IE ECMA
2+ 4+ ECMA 1

Methods
concat() join() pop() push() reverse() shift() slice() Combines two existing Array objects to one Returns a string with elements from an Array Removes the last value from an Array. Appends a value to the end of an Array. Reverse the order of elements in an Array. Removes the first value from an Array. Returns a subset from an Array.

NN IE ECMA
3+ 4+ ECMA 1 2+ 4+ ECMA 1 3+ 5.5+ ECMA 1 3+ 5.5+ ECMA 1 2+ 4+ ECMA 1 3+ 5.5+ ECMA 1 3+ 4+ ECMA 1

Sorts an Array. Adds new elements to an Array while removing old splice() elements. toLocaleString() Returns a String with current locale format and separators. toSource() String representing the source code of the object. Returns Array elements as string type separated by toString() commas. unshift() Inserts a value at the beginning of an Array. Returns Array elements as string type separated by valueOf() commas. sort()

2+ 4+ ECMA 1 3+ 4+ ECMA 1 n/a 4+ ECMA 1 4+ n/a n/a 2+ 4+ ECMA 1 3+ 5.5+ ECMA 1 2+ 4+ n/a

Properties
constructor index input length prototype Reference to the function that created an object. Zero-based index of the match for array created by a regular expression match. Original string used to match for array created by a regular expression match. Returns the length of an Array Creates a new method for Array objects

NN IE ECMA
2+ 4+ ECMA 1 3+ 4+ n/a 3+ 4+ n/a 2+ 4+ ECMA 1 2+ 4+ ECMA 1

Array
Multidimensional variable

Core object

Syntax:
Syntax 1 var myArray = new Array()

Syntax 2 var myArray = new Array(sizeInteger)

Syntax 3 var myArray = new Array(element0, element1, ..., elementN)

Browser support:
Microsoft Internet Explorer: 4+ Netscape Browser: 2+

Implementations:
JavaScript 1.1 (by Netscape) JScript 2 (by Microsoft) ECMA Script 1 (ECMA Standard)

Example:
Example 1 : var myArray = new Array(); myArray[0]='Mercedes'; myArray[1]='Volvo'; alert('The last car is a '+myArray[1]);

Example 2 : var myArray = new Array('Mercedes','Volvo'); alert('The last car is a '+myArray[1]);

JavaScript Objects :

BOOLEAN OBJECT
Core Object
Boolean Variable representing true or false.
2+

- Printable Version - Send Page To Frien

NN IE ECMA
4+ ECMA 1

Methods
toSource() toString() valueOf() String representing the source code of the object. Returns boolean value as string type. Returns an objects value as a Boolean type.

NN IE ECMA
4+ 2+ 2+ n/a n/a 4+ ECMA 1 4+ ECMA 1

Properties
constructor prototype Reference to the function that created an object. Creates a new method for Boolean objects

NN IE ECMA
2+ 2+ 4+ ECMA 1 4+ ECMA 1

Boolean
Variable representing true or false.

Core object

Syntax:
Syntax 1 var myBoolean = new Boolean()

Syntax 2 var myBoolean = new Boolean(booleanValue)

Syntax 3 var myArray = booleanValue

Browser support:
Microsoft Internet Explorer: 4+ Netscape Browser: 2+

Implementations:
JavaScript 1.1 (by Netscape) JScript 2 (by Microsoft) ECMA Script 1 (ECMA Standard)

Example:
Example 1 : var myBoolean = false; alert(myBoolean);

Example 2 : var myBoolean = false; var yourBoolean = true; if (myBoolean) alert('myBoolean is true'); if (yourBoolean) alert('yourBoolean is true');

DATE OBJECT
Core Object
Date Date and time object.
2+ 3+

- Printable Version - Send Page To Frien

NN IE ECMA
ECMA 1

Methods
getDate() getDay() getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCFullYear() Date as an integer between 1 and 31. Day of week value: 0=Sunday, 1=Monday... 4 digit year of a Date object. Hours value of a Date object (0-23). Milliseconds value of a Date object (0-999) Minutes value of a Date object (0-59) Month value of a Date object. (0=Jan, 11=Dec) Seconds value of a Date object. (0-59) Milliseconds since 1970-1-1 of a Date object. Minutes between local and UTC (GMT) time. Date value using UTC (GMT) time. (1-31) Day of week using UTC (GMT) time. (0=Sunday) 4 digit year using UTC (GMT) time.

NN IE ECMA
2+ 3+ 2+ 3+ 4+ 4+ 2+ 3+ 4+ 4+ 2+ 4+ 2+ 3+ 2+ 3+ 2+ 3+ 2+ 3+ 4+ 4+ 4+ 4+ 4+ 4+ ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1

getUTCHours() getUTCMilliseconds() getUTCMinutes() getUTCMonth() getUTCSeconds() getVarDate() getYear() parse() setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime() setUTCDate() setUTCFullYear() setUTCHours() setUTCMilliseconds() setUTCMinutes() setUTCMonth() setUTCSeconds() setYear() toDateString() toGMTString() toLocaleDateString() toLocaleString() toLocaleTimeString() toSource() toString() toTimeString() toUTCString() UTC() valueOf()

Hours using UTC (GMT) time. (0-23) Milliseconds using UTC (GMT) time. (0-999) Minutes using UTC (GMT) time. (0-59) Month using UTC (GMT) time. (0-11). Seconds using UTC (GMT) time. (0-59) Visual Basic compatible VT_DATE value. Year value of a Date object. Milliseconds between parsed string and 1970-1-1 Sets the date of the Date object. Sets the year value in a Date object. Sets the hours value in a Date object. Sets the milliseconds value in a Date object. Sets the minutess value in a Date object. Sets the month value in a Date object. Sets the seconds value in a Date object. Sets the time value (milliseconds) in a Date object. Sets the UTC date of a Date object. Sets the UTC year value in a Date object. Sets the UTC hours value in a Date object. Sets the UTC milliseconds value in a Date object. Sets the UTC minutess value in a Date object. Sets the UTC month value in a Date object. Sets the UTC seconds value in a Date object. Sets the year value of a Date object. Returns a date as a string value. String value of a Date objects GMT time. Returns a date as a string value. String value of a Date object, in local time format. Returns a time as a string value. String representing the source code of the object. String representation of a Date object Returns a time as a string value. Date converted to string using UTC. Milliseconds since 1970 using UTC time. Milliseconds since 1970-1-1.

4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ n/a 4+ 2+ 3+ 2+ 3+ 2+ 4+ 4+ 4+ 2+ 4+ 4+ 4+ 2+ 3+ 2+ 3+ 2+ 3+ 2+ 3+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 4+ 2+ 3+ 2+ 3+ 2+ 3+

ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 n/a ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1 ECMA 1

n/a 5.5+ n/a n/a 5.5+ n/a n/a 5.5+ n/a 4+ n/a ECMA 1 2+ 4+ 4+ 4+ 2+ 3+ 2+ 4+ ECMA 1 ECMA 1 ECMA 1 ECMA 1 n/a 5.5+ n/a

Properties
constructor prototype Reference to the function that created an object. Creates a new method for Date objects

NN IE ECMA
2+ 4+ 2+ 4+ ECMA 1 ECMA 1

Date
Date and time object.

Core object

Syntax:
Syntax 1 var myDate = new Date()

Syntax 2 var myDate = new Date([parameters])

Syntax 3 var myDate = new Date(dateString)

Syntax 4 var myDate = new Date("month dd, yyyy")

Syntax 5 var myDate = new Date("month dd, yyyy hh:mm:ss")

Syntax 6 var myDate = new Date(yy, mm, dd)

Syntax 7 var myDate = new Date(yy, mm, dd, hh, mm, ss)

Syntax 8 var myDate = new Date("miliseconds")

Browser support:
Microsoft Internet Explorer: 3+ Netscape Browser: 2+

Implementations:
JavaScript 1.0 (by Netscape) JScript 1 (by Microsoft) ECMA Script 1 (ECMA Standard)

Example:
Example 1 : var myDate=new Date(); alert('Right now it is: '+myDate.toLocaleString());

Example 2 : myDate = new Date("October 13, 1966 13:35:00"); weekdays=new Array('Sun','Mon','Tues','Wednes','Thurs','Fri','Satur'); alert('I was born a '+weekdays[myDate.getDay()]+'day.');

Example 3 : // Note: October is month number 9! (Cause January is 0) // The reason for this is that it fits well for Arrays, // cause first item in an Array is item number zero. // Look at this example: myDate = new Date(1966,9,13); months=new Array('Jan','Feb','Mar','Apr','May','June', 'July','Aug','Sep','Oct','Nov','Dec'); alert('I was born in '+months[myDate.getMonth()]);

Example 4 : myDate = new Date(1966,9,13,13,35,0); nowDate = new Date(); milliseconds=nowDate.getTime()-myDate.getTime(); days=Math.floor(milliseconds/(1000*60*60*24)); alert('I have lived for '+days+' days.');

Example 5 : myDate = new Date(1966,9,13,13,35,0); nowDate = new Date(); milliseconds=nowDate.getTime()-myDate.getTime(); hours=Math.floor(milliseconds/(1000*60*60)); alert('I have lived for '+hours+' hours.');

Example 6 : nowDate = new Date(); xmasDate = new Date(nowDate.getYear(),11,24); milliseconds=xmasDate.getTime()-nowDate.getTime(); days=Math.floor(milliseconds/(1000*60*60*24)); alert('There are '+days+' days left till christmas eve.');

FUNCTION OBJECT
Core Object
Function Creates a new function.
2+ 4+

- Printable Version - Send Page To Frien

NN IE ECMA
ECMA 1

Methods
apply()

NN IE ECMA
Applies a method of another object to the current object. 4+ 5.5+ n/a

call() toSource() toString() valueOf()

Executes method of another object on current object. String representing the source code of the function. String representing the source code of the function. String representing the source code of the function.

4+ 5.5+ n/a 4+ n/a n/a 2+ 4+ 2+ 4+ ECMA 1 ECMA 1

Properties
arguments arguments.callee arguments.length caller constructor length prototype An array with the arguments passed to a function. The function body of the currently executing function. Number of arguments passed to the function. Reference to the function that created an object. Reference to the function that created an object. Number of arguments expected by the function. Creates a new method for Function objects.

NN IE ECMA
2+ 4+ ECMA 1 2+ 5.5+ ECMA 1 2+ 5.5+ ECMA 1 3+ 4+ 2+ 4+ 2+ 4+ 2+ 4+ ECMA 1 ECMA 1 ECMA 1 ECMA 1

Function
Creates a new function.

Core object

Syntax:
Syntax 1 function functionName([argname1 [, ...[, argnameN]]]){ body }

Syntax 2 functionName = new Function( [argname1, [... argnameN,]] body );

Browser support:
Microsoft Internet Explorer: 4+ Netscape Browser: 2+

Implementations:
JavaScript 1.1 (by Netscape) JScript 2 (by Microsoft) ECMA Script 1 (ECMA Standard)

Example:
Example 1 : function myFunction(){

alert('I AM ALIVE'); }

Example 2 : <html> <head> <title>Example page</title> <script language="JavaScript"> function myMessenger(message){ alert('IMPORTANT MESSAGE: '+message); } </script> <body onLoad="myMessenger('PAGE IS LOADED')"> Bla, bla, bla <a href="#" onClick="myMessenger('YOU HIT THE LINK!');">CLICK HERE</a> </body> </html>

MATH OBJECT
Core Object
Math Object with math functionality and constants.

- Printable Version - Send Page To Frien

NN IE ECMA
2+ 3+ ECMA 1

Methods
Returns the absolute value of a number. Returns the arccosine (in radians) of a number. Returns the arcsine (in radians) of a number. Returns the arctangent (in radians) of a number. Returns the arctangent of the quotient of its arguments. Returns the smallest integer greater than or equal to a number. Returns the cosine of a number. Returns e (the base of natural logarithms) raised to a power. Returns the largest integer less than or equal to a number. Returns the natural logarithm (base E) of a number. Returns the greater of two numbers. Returns the lesser of two numbers. Returns the value of a base expression taken to a specified pow() power. random() Returns a pseudo random number between 0 and 1. round() Returns the value of a number rounded to the nearest integer. sin() Returns the sine of a number. sqrt() Returns the square root of a number. tan() Returns the tangent of a number. abs() acos() asin() atan() atan2() ceil() cos() exp() floor() log() max() min()

NN IE ECMA
2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1

Properties
E LN2 LN10 LOG2E LOG10E PI SQRT1_2 SQRT2 Euler's constant, approximately 2.718. Natural logarithm of 2, approximately 0.693. Natural logarithm of 10, approximately 2.302. Base 2 logarithm of E, approximately 1.442. Base 10 logarithm of E, approximately 0.434. The value of PI, approximately 3.14159. Square root of 1/2, approximately 0.707. Square root of 2, approximately 1.414.

NN IE ECMA
2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1 2+ 3+ ECMA 1

Math
Object with math functionality and constants.

Core object

Syntax:
Syntax 1 Math.property(value)

Syntax 2 Math.method(value)

Browser support:
Microsoft Internet Explorer: 3+ Netscape Browser: 2+

Implementations:
JavaScript 1.0 (by Netscape) JScript 1 (by Microsoft) ECMA Script 1 (ECMA Standard)

Example:
Example : alert('The square root of 4 is: '+Math.sqrt(4));

NUMBER OBJECT

- Printable Version - Send Page To Frien

Core Object
Number Object for primitive numeric values.

NN IE ECMA
3+ 3+ ECMA 1

Methods
toLocaleString() toString() valueOf()

NN IE ECMA
String value of a Number object, in local value n/a 3+ ECMA 1 format. 3+ 3+ ECMA 1 Returns a string representing the object. The numeric value. (no effect for Number objects.) 2+ 4+ ECMA 1

Properties
constructor MAX_VALUE MIN_VALUE NaN NEGATIVE_INFINITY POSITIVE_INFINITY prototype Reference to the function that created an object. Largest number representable. (~1.79E+308). Smallest number representable. (~5.00E-324) Special "not a number" value. Negative infinity, displayed as "-Infinity". Positive infinity, displayed as "Infinity". Creates a new method for Number objects

NN IE ECMA
2+ 4+ ECMA 1 3+ 3+ ECMA 1 3+ 3+ ECMA 1 3+ 3+ ECMA 1 3+ 3+ ECMA 1 3+ 3+ ECMA 1 2+ 4+ ECMA 1

Number
Object for primitive numeric values.

Core object

Syntax:
numberObject=new Number(value);

Browser support:
Microsoft Internet Explorer: 3+ Netscape Browser: 3+

Implementations:
JavaScript 1.2 (by Netscape) JScript 1 (by Microsoft) ECMA Script 1 (ECMA Standard)

Example:
Example : // The following example creates a Number object, myNum, // then adds a description property to all Number objects. // Then a value is assigned to the myNum object's description property.

myNum = new Number(65); Number.prototype.description=null; myNum.description="wind speed" alert('The '+myNum.description+' is: '+myNum); // Would alert: The wind speed is 65

OBJECT OBJECT
Core Object
Object Provides functionality common to all JavaScript objects.

- Printable Version - Send Page To Frien

NN IE ECMA
2+ 4+ ECMA 1

Methods
toLocaleString() toSource() toString() unwatch() valueOf() watch() String value of an object, in local value format. Object literal representing the specified object. Returns a string representing the object. Removes a watchpoint set with the watch method. Primitive value of the specified object. Runs a function when specific property is assigned value.

NN IE ECMA
n/a 3+ ECMA 1 4+ n/a n/a 2+ 3+ ECMA 1 3+ n/a n/a 2+ 4+ ECMA 1 3+ n/a n/a

Properties
constructor prototype Reference to the function that created an object. Creates a new method for Number objects

NN IE ECMA
2+ 4+ ECMA 1 2+ 4+ ECMA 1

Object
Provides functionality common to all JavaScript objects.

Core object

Syntax:
objectName=new Object([value]);

Browser support:
Microsoft Internet Explorer: 4+ Netscape Browser: 2+

Implementations:
JavaScript 1.0 (by Netscape) JScript 3 (by Microsoft) ECMA Script 1 (ECMA Standard)

Example:

Example : point = new Object(); point.x=17; point.y=22; alert(point.x+' : '+point.y) // Would alert: 17 : 22

STRING OBJECT
The string object makes it easier to handle strings. The following methods and properties are available for strings:
Note:
In the examples, we assume that a variable called MyString has been assigned the value "Go Johnny, Go Go Go".
OBJECT
length

- Printable Version - Send Page To Frien

EXPLANATION Returns the length of the string MyString.length would return 19 Returns the character at the specified position in the string. MyString.charAt(3) would return the character "J". Note: J is the fourth character in the string, but since counting starts with 0 the fourth character is referred to as number 3. Returns the character code at the specified position in the string.

charAt(n)

charCodeAt(n)

MyString.charCodeAt(4) would return the value 74. The reason is that J is character #74 in the so called ISO-Latin-1 codeset. Returns the first position of the substring. MyString.indexOf("Go") would return 0.

indexOf(string[,n])

Note: If a substring is at the beginning of a string the position is zero. If a substring is not present within a string the value is -1.

MyString.indexOf("Go",3) would return 11. Note: The search for "Go" starts at the third character, but the counting still starts at the first. The first presence of Go (if presence before the third character is omitted) is at the 12th character. Since the first character is referred to as number zero the result is 11. Returns the last position of the substring. MyString.lastIndexOf("Go") would return 17.
lastIndexOf(substring[,n])

Note: If a substring is at the beginning of a string the position is zero. The last position in a string is therefore one less than the length of the string. If a substring is not present within a string the value is -1. Constructs a string from the specified sequence of ISO-Latin-1 codeset values

fromCharCode(x[,y,z])

String.fromCharCode(74,75,76) would return "JKL". Returns the specified subset of the string, by specifying the start and end indexes MyString.substring(3,9) would return "Johnny".
substring(x,y)

Note: The first character is number zero. x indicates the start of the substring. y indicates the end of the substring. Thus, y is NOT the number of characters to include, starting at character x. Returns the string in all lowercase

toLowerCase()

MyString.toLowerCase() would return "go johnny, go, go, go". Returns the string in all uppercase

toUpperCase()

MyString.toUpperCase() would return "GO JOHNNY, GO, GO, GO". Splits a string into an array of strings by separating the string into substrings

split(separator[,n])

MyArrayOfS=MyString.split(", ") would result in the creation of an array: MyArrayOfStrings[0] would be "Go Johnny"

MyArrayOfStrings[1] would be "Go" MyArrayOfStrings[2] would be "Go" MyArrayOfStrings[3] would be "Go" The number of elements in the array is stored in MySplitString.length.

MyArrayOfStrings=MyString.split(", ",2) would result in a different array: MyArrayOfStrings[0] would be "Go Johnny" MyArrayOfStrings[1] would be "Go" By entering a limit on the number of splits, we reduced the array to 2 entries.

NOTE: Javascript 1.2 or higher!


Does exactly the same as substring.
slice(x,y)

NOTE: Javascript 1.3 or higher!


Returns a subset of a string. This is almost the same as substring. The difference is that, in substring you enter startindex and endindex, while in substr you enter startindex and numbers of characters to include. substr(3,6) would return "Johnny", which is the same as substring(3,9)

substr(x,y)

NOTE: Javascript 1.3 or higher!


Compare variables.
match

Use this syntax instead: if(varibel1==variabel2) {bla bla bla}

NOTE: Javascript 1.3 or higher!


Replaces substrings of a string. MyString.replace(/Go/, "Up") would return "Up Johnny, Go, Go, Go".
replace(/subtext/[gi])

MyString.replace(/Go/g, "Up") would return "Up Johnny, Up, Up, Up". /Go/g forces a global replace. Not just replacing of the first "Go".

MyString.replace(/go/gi, "Up") would return "Up Johnny, Up, Up, Up". /go/i forces the replace to ignore upper and lower case differences.

NOTE: Javascript 1.3 or higher!


Searches for substrings in a string.
search

Use substring instead.

NOTE: Javascript 1.3 or higher!


Click here for the object definition provided by DevEdge.

NAVIGATOR OBJECT
The navigator object contains information about the browser.
OBJECT
appCodeName appName appVersion userAgent mimeTypes plugins javaEnabled plugins.refresh taintEnabled platform language preference

- Printable Version - Send Page To Frien

EXPLANATION Specifies the code name of the browser. Specifies the name of the browser. Specifies version information for the browser. Specifies the user agent header. An array of all MIME types supported by the visitors browser. An array of all plug-ins currently installed on the visitors browser. Tests whether Java is enabled.

DEF NS2+ NS2+ NS2+ NS2+ NS3+ NS3+ NS3+

Makes newly installed plug-ins available and can reload NS3+ windows containing plug-ins. Specifies whether data tainting is enabled Indicates the platform (Win32, Unix, etc.) for which the browser was compiled. Indicates the language version of the browser (ex: UK, De, Dk). Allows a signed script to get and set certain Navigator preferences. NS3+ NS4+ NS4+ NS4+

Note: DEF indicates which version of Netscape Browsers that introduced the object. You can click the DEF link to get the complete object documentation provided by DevEdge.

You might also like