
JavaScript is a scripting language that will allow you to
add real programming to your webpages.You can
create small application-like things with Javascript, like a Calculator or a primitive
game of some kind. However, there are more serious uses for javascript.
| Browserdetection |
| Detecting the browser used by a visitor
at your page. Depending on the browser another page especially designed for that browser
can then be loaded. |
| |
| Cookies |
| Storing information on the visitors
computer and then retrieve this information automatic next time the user visits your page.
This technique is called cookies. |
| |
| Control
Browsers |
| Opening pages in customized windows,
where you specify if the browsers buttons, menuline, statusline or whatever should be
present. |
| |
| Validate Forms |
Validating inputs to fields before
submitting a form.
An example would be to validate the entered email address to see if it has an @ in it,
since, if not, it's not a valid address. |
WHERE TO PLACE IT
Since javascript basically isn't HTML you will need to let the
browser know in advance when you enter javascript to a HTML-page. This is done using the
<script>-tag.
The browser will use the <script
language="JavaScript"> and </script> to tell where JavaScript starts
and ends.
<html>
<head>
<title>My JavaScript-page<title>
</head>
<body>
<script language="JavaScript">
alert("Welcome to my world!!!");
</script>
</body>
</html> |
The word alert is a standard javascript-command that will
cause an alertbox to pop-up on the screen. The visitor will need to click the
"OK"-button in the alertbox to proceed.
By entering the alert-command between the
<script language="JavaScript">
and </script>-tags the
browser will recognize it as a javascript-command.
If we had not entered the <script>-tags the browser would simply
recognize it as pure text, and just write it on the screen.
You can enter javascript sections in both
the <head> and <body>-sections of the
document.
In general, however, it is advised to keep as much as possible in the head-section.
THE FIRST SCRIPT
Knowing that javascript needs to be entered
between <script>-tags there are a few other things you need
to know before writing your first JavaScript.
First of all: you may have noticed from the above example that JavaScript-lines ends with a semi-colon.
You can easily put all your JavaScript on a single line without destroying the performance
of it.
However you'd destroy the overview of your script so it's not adviceable.
Second, 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.
Third you should always remember that capital
letters are different from non-capital letters.
This means, that when you write commands in JavaScript you need to type capital letters at
exact the right places, and nowhere else.
For instance one JavaScript-command is called onMouseOver. If you typed Onmouseover instead you might as well have typed qwHETwer iuh since JavaScript just doesn't
understand it.
Messing up with capital letters 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 pop-up-box we could have it write it 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 that tells the browser that what follows within the parenthesis is to
be written into the document.
Note that when entering text in javascript you need to include it in " ".
The script in the example would produce this output on your page:
Consider
this example to see where javascript would write the text:
<html>
<head>
<title>My JavaScript-page<title>
</head>
<body>
Hello!!!<br>
<Script>
document.write("Welcome to my world!!!");
</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!
Capital LETTERS
It is extremely important to be
aware that javascript makes a sharp distinction between capital- and non-capital
letters. JavaScript does not consider a variable named "myvalue" to be the same
as a variable named "MYVALUE".
Consider these examples:
| Example 1 |
Example 2 |
<html>
<head>
<title>My JavaScript-page<title>
</head>
<body>
<script>
myvalue=2;
myvalue=5;
result=myvalue+myvalue;
document.write(result);
</script>
</body>
</html> |
<html>
<head>
<title>My JavaScript-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).
POPUP-BOXES
It is possible to make three different kinds of
popup-windows.
Try click the buttons below to see the differences:
ALERTBOX
The syntax for an alertbox is: alert("yourtext");
The user will need to click
"Ok" to proceed.
Typical use is when you want to make sure an 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-plugin").
CONFIRMBOX:
The syntax for a confirmbox is:
confirm("yourtext");
The user need to
click either "OK" or "Cancel" to proceed.
Typical use is when you want the user to agree to or accept
something.
Examples could be age-verification like "Confirm that you are
at least 21 years old" or technical matters like "Do you have a plugin for
Shockwave Flash?"
- If the user click "OK", the
box returns the value true.
- If the user click "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 on
this page.
PROMPTBOX:
The promptbox 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 users name to be
stored in a cookie or entering a password or code of some kind.
- If the user clicks "OK" the promptbox returns the
entry.
- If the user clicks "Cancel" the promptbox returns null.
Since you usually want to use the input from the promptbox for some
purpose it is normal to store the input in a variable, as shown in the example below:
| username=prompt("Please enter your
name","Enter your name here"); |
UNDERSTANDING
VARIABLES
Variables can be compared to small boxes with names on.
If you were to store 5 pair of shoes, you might have a box for each
pair.
On each box you would write what was 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.
A variable is simply a place in the computers 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> |
In this example we would write
"Henrik" in the document.
Notice 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 differ text from variables.
Look at this example to see the
importance of including text in " ".
<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 what will be written on the screen from this example
before reading on.
- In the second line the text "my
first name" is stored in the Henrik-variable.
- In the third line the Henrik-variable is stored in the myname-variable.
- Finally in line 4 the myname-variable is written to the document.
The result is that
"my first name" will be written on the screen.
ASSIGNING VALUES TO VARIABLES
The most common way to assign a value to a variable is using the
equal-sign.
Consider these examples to see the different ways variables can be
assigned to contain either values or text.
Note in particular how parenthesis can be used to control how complex formulas are
handled.
| Example |
Resulting value |
a=2;
a=2; a++;
a=2; a--;
a=2; b=a++;
a=2; b=3; c=a+b;
a=2; d=a+6;
FirstName="Henrik";
LastName="Petersen";
FullName=FirstName+" "+LastName;
a=2*7;
b=20/5;
c=(20/5)*2;
d=20/(5*2); |
a=2
a=3 (2+1)
a=1 (2-1)
b=3 (2+1)
c=5 (2+3)
d=8 (2+6)
FirstName=Henrik
LastName=Petersen
FullName=Henrik Petersen
a=14 (2*7)
b=4 (20/5)
c=8 (4*2)
d=2 (20/10) |
The 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 type a=a+1;.
| Operator |
Explanation |
Example |
| ++ |
increment |
a=5;
a++;
a would now be 6 |
| -- |
decrement |
a=5;
a--;
a would now be 4 |
| % |
returns modulus,
which is what is left when two
numbers are divided. |
a=8 % 3;
a would now be 2,
since 8 can be divided by 3
two times leaving a rest of 2. |
COMPARING VARIABLES
There are several different ways to compare variables.
The most simple is comparing for equality, which is done using a double equal-sign:
if (a==b) {alert("a
equals b")};
if (lastname=="Petersen") {alert("Nice name!!!")};
Note: The if-statement is explained in details in the next section
of this page.
If you forget to use double equal-signs
when comparing variables for equality, and uses single equal signs instead, you will not
compare the variables. What will happen is, that the variable on the left side of the
equal-sign will be assigned the value of the varible to the right.
This is a very common bug that will totally ruin the script.
The table below contains the different
comparing operators:
| Operator |
Explanation |
Example |
| == |
equal to |
4==5 (false)
5==5 (true)
5==4 (false) |
| != |
not equal to |
4!=5 (true)
5!=5 (false)
5!=4 (true) |
| < |
lesser than |
4<5 (true)
5<5 (false)
5<4 (false) |
| > |
greater than |
4>5 (false)
5>5 (false)
5>4 (true) |
| <= |
lesser than or equal to |
4<=5 (true)
5<=5 (true)
5<=4 (false) |
| >= |
greater than or equal to |
4>=5 (false)
5>=5 (true)
5>=4 (true) |
In the Function-section you will learn more
about global and local variables.
In the Array-section you will learn more about ways to work with
large amounts of variables.
IF
& ELSE
Often your JavaScripts requires the ability to make
distinctions between different possibilities.
For instance, you might have a script that checks which browser the user arrives with.
If it's MSIE a page specially designed for that browser should be loaded, if it's Netscape
another page should be loaded.
The general syntax for if-statements is
this:
if (condition) {action1} else {action2};
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 capitals would cause an error.
Also note that when comparing variables you will need to have two
equalsigns next to each other.
If we wrote browser="MSIE"
we would actually store "MSIE" in the variable called browser.
By writing browser=="MSIE"
the browser will know that we want it to compare instead.
You will learn more about operators (=, <, >
etc.) in the next section.
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 of a more complex if-statement
is this:
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 might benefit from the
so-called logical operators.
And is written as && and is used when you want to check if more than
one condition to be true.
Ex: If the basket contains egg and the basket contains bacon, we can have egg and bacon.
In javascript the syntax would be: 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.
Ex: If the basket contains milk or the basket contains water, we can have something to
drink.
In javascript the syntax would be: 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 whatever you are checking for.
Ex: If not the basket contains egg or not the basket contains bacon, we cant have egg and
bacon.
In javascript the syntax would be: if (!(condition)) {action}
| if (!(hour=11)) {alert("it's more than 1 hour till noon")}; |
Functions
Instead of just adding your javascript to the page and have
the browser perform the tasks as soon as the script is read, you might want your
javascript to be performed only upon the detection of a certain even.
For example, if you made a javascriptcode that changed the background color of the page
when the user clicked a button, you would need to tell the browser, that the script
changing the background color of the page, 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 asks for it. This way
you gain complete control of the timing.
Below is an example of scriptlines
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 shown below to see what the script in the example does:
In the code shown above the
alertbox does not appear until the user clicks the button.
If the line: alert("Welcome to my world"); had not been written within a function it would simply have been
performed as soon as the line was loaded by the browser. But since we wrote it as a
function, it is not performed until the browser is specifically told to.
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 event onClick="myfunction()" to the properties of the button. The next section of this page gives a
detailed description of the different events you could use to call functions.
The general syntax
for functions is this:
function
functionname(varible1, varible2,..., variableX)
{
// Here goes the javascriptlines for the function
}
The { and the } marks the start and end of the function.
A typical bug when
entering javascriptfunctions is to forget about the importance of capitals in javascript.
The word "function" needs to be spelled exactly as "function".
"Function" or "FUNCTION" would not be valid.
Furthermore, use of
capitals matters in the name of the function as well. If, say, you had a function called myfunction() it would not be
valid to call it Myfunction(), MYFUNCTION() or MyFunction() when referring to it.
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 up-state, and
another image that shows the button in down-state.
If this function is called using a 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 |
Explanation |
HTML-tags |
| onFocus="" |
A formfield gets focus |
Select, Text, Textarea |
| onBlur="" |
A formfield looses focus |
Select, Text, Textarea |
| onChange="" |
The content of a formfield is changed |
Select, Text, Textarea |
| onSelect="" |
The user marks text in a formfield |
Text, Textarea |
| onMouseOver |
The mouse moves over a link. |
A |
| onMouseOut |
The mouse moves out of a link |
A |
| onClick="" |
The mouse clicks on an object |
A, Button, Checkbox,
Radio, Reset, Submit |
| onLoad="" |
The page is finished loading |
Body, Frameset |
| onUnload="" |
The browser opens another document |
Body, Frameset |
| onSubmit="" |
The user clicks the submitbutton of a form |
Form |
Events are used for two main
purposes:
1) To perform a function upon detection of the event, and/or
2) To show a pop-up-box upon detection of the event.
Below is a brief description with
examples of the main purposes for the different events.
onFocus,
onBlur and onChange are mainly used in combination with
validation of formfields.
Lets say you had a function called validateEmail()
that would check if an entered emailaddress has an @ in it, and if it has a meaningful
end, such as "com", "net" or whatever. Furthermore, suppose the user
could enter his emailaddress 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
formfield-validation.
onLoad
and onUnload are mainly used
for pop-up's that appears when the user enters or leaves the page. Another important use
is in combinations with cookies that should be set upon
arrival or leaving your pages.
For example you might have a pop-up 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 is storing the current
date.
Next time the visitor arrives at your page it will have another pop-up 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 pop-up-boxes.
Another more or less common use of the onLoad and onUnload-events
is this: Some annoying pages has a function that immediately opens several other windows
as soon as you enter the page. This is a clear break of the 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 formfield. Some times, however, the visitor might
find it annoying to have validations in the middle of the entering of 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 script called a
function named checkform()
that would validate entries to a form. Now you want this function to be called when the
user clicks the submitbutton. If the content is not accepted by your function the submit
should be cancelled. This way nothing would be submitted unless you function accepted the
content.
What you should do, is add the onSubmit to the <form>-tag
this way:
| <form method="yourchoise" action="yourchoise" onsubmit="return
checkform()"> |
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 make 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 bookmark, as shown in the example below).
Below is shown how to make an alertbox appear when a
onMouseOver is detected on an image:
The code to produce the above example is this:
<a
href="#"
onMouseOver="alert('I detected an onMouseOver-event')"
onMouseOut="alert('I detected an onMouseOut-event')">
<img src="rainbow.gif" width="60"
height="60">
</a> |
Note: The href="#" makes the image link 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 bookmarks.
Click here to learn more about alert-boxes.
Loops
Imagine that you wanted a script to
perform the same routine over and over again 50 times in a row.
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 the similar task - in the example above it would be if you wanted it to create
exactly 50 lines.
You would simply tell the script to loop the same lines 50 times in a row.
The while-loop is used when you don't know in advance how many times the loop
should be performed. You simply want the loop to be performed until a certain condition
becomes true. In the example above it would be 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 say 1200 degrees of Celsius.
You would simply tell the script to perform the loop until Degrees Celsius was above 1200.
Below is a
description of each of these two loops:
| SYNTAX: |
for (variable=startvalue; variable<=endvalue; variable=variable+incrementfactor)
{
// Here goes the scriptlines you want to be looped.
} |
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, eg. >,
== or whatever. |
| EXAMPLE: |
<html>
<head>
<title>Celsius-Fahrenheit-converter</title>
</head>
<body>
<table border=3>
<tr><td>CELCIUS</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.
| SYNTAX:
|
while
(variable<=endvalue)
{
//
Here goes the scriptlines you want to be looped.
} |
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 eg. >,
== or whatever.
|
| EXAMPLE: |
|
<html>
<head>
<title>Celsius-Fahrenheit-converter</title>
</head>
<body>
<table border=3>
<tr><td>CELCIUS</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.
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 square-root 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
When working with more complex scripts you might face a
situation in which you would have many more or less similar variables.
Instead of being forced to write a line for each operation done to such a variable, you
can use arrays to help you automatize the proces.
| Example 1 |
Example 2 |
value1=10;
value2=20;
value3=30;
....
here would go 96 similar lines
....
value100=1000 |
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.
To use variable-arrays you need to define the array before
referring to any of the variables in it.
This is done using the syntax: variablename=new Array;
Replace variblename with the
varible you want to work as an array.
As the example shows arrays becomes
extremely powerfull when used in combination with loops.
However you do not have to handle array-variables in loops.
Single variables can be addressed with a syntax like this: value[9]=170;
When you feel comfortable with the basic javascript explained in
this section you should continue by learning about the javascript-objects.
Objects are pre-defined functions for maths,
textvariableoperations, 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 (formfields, buttons, images, browser-menus and
browserbuttons etc etc) on the pages.
That is where you really start taking your pages beyond the
average.
Click here to explore the power of the JavaScript
built-in-objects.
|