Professional Documents
Culture Documents
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>
Note: When entering text in javascript you need to include it in " ".
As you can see, javascript simply writes the text to where the script is placed
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.
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.
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.
POP UP BOXES
It is possible to make three different kinds of popup windows. Try clicking the buttons below to see the differences:
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")};
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.
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 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.
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.
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.
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=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 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.
This is a very common bug that will totally ruin the script.
Explanation equal to
5==5 (true)
5==4 (false)
4!=5 (true)
!=
not equal to
5!=5 (false)
<
>
greater than
<=
>=
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.
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.
Also note that when comparing variables you will need to have two equals signs
next to each other (==).
The next section explains the different operators (=, <, > etc.).
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")};};
Ex: If the basket contains egg and the basket contains bacon, we can have egg
and bacon.
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.
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.
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.
Click the button to see what the script in the example does:
But since we wrote it as a function, it was not performed until you hit the button.
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 { 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
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.
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.
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
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()">;
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".
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()">
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).
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.
LOOPS
50 times in a row.
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
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.
FOR LOOPS:
SYNTAX:
for (variable=startvalue; variable<=endvalue;variable=variable+incrementfactor) {
// Here goes the script lines you want to loop.
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>
WHILE LOOPS:
SYNTAX:
while (variable<=endvalue) {
// Here goes the script lines you want to loop.
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;
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.
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.
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.
Example 2
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.
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.
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.
JAVASCRIPT TUTORIAL
webpages.
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.
If you're completely new to JavaScript you should start with the section that covers
JavaScript Basics.
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
Browser Detection :
THE TECHNIQUE
Browser detection is based on the navigator object.
This object holds name, version, etc. of the browser.
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:
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:
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:
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.
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)
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".
<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.
In this example we send Netscape visitors to Yahoo, while we send MSIE visitors
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)
// 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.
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.
If you're completely new to JavaScript you should start with the section that covers
JavaScript Basics.
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
Advanced Scripts :
ANIMATED BUTTONS
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.
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.
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
Animated Buttons :
THE CODE
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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
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
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.
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.
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.
Finally you need to add the desired URL and the optional target to each of the
options in the menus.
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"
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.
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.
{ 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.
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:
emailvalidation will check to see if a value lives up to the general syntax of an email.
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)
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.
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.
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.
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.
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.
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';
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.
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.
THE TECHNIQUE
This script ensures that subpages aren't loaded outside a frameset.
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.
As mentioned on the previous page, you need to enter a small script in the<head> section of both
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.
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.
<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.
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:
subpage.htm--A secondary page that can be loaded into the right frame
window.
When you click the links to the sample page, it will open in a new window. Just
close that window to return back here.
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>
If you want a link to open a document in a new regular window you should not use
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).
THE TECHNIQUE
JavaScript has built-in methods for opening and closing windows.
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:
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.
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
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.
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=
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>
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
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()
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]);
JavaScript Objects :
BOOLEAN OBJECT
Core Object
Boolean Variable representing true or false.
2+
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()
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+
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 7 var myDate = new Date(yy, mm, dd, hh, mm, ss)
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+
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
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.
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 }
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.
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
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.
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
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.
substr(x,y)
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.
NAVIGATOR OBJECT
The navigator object contains information about the browser.
OBJECT
appCodeName appName appVersion userAgent mimeTypes plugins javaEnabled plugins.refresh taintEnabled platform language preference
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.
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.