JavaScript Basics : 2

INTRODUCTION.. 2

WHERE TO PLACE IT. 2

POP UP BOXES.. 7

VARIABLES.. 9

IF AND ELSE.. 13

FUNCTIONS.. 16

EVENTS.. 18

LOOPS.. 22

ARRAYS.. 26

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

JavaScript Basics :

INTRODUCTION


Javascript is a scripting language that will allow you to add real programming to your webpages.

You can create small application type processes with javascript, like a calculator or a primitive game of some sort.

However, there are more serious uses for javascript:

 

 

WHERE TO PLACE IT


Since javascript isn't HTML, you will need to let the browser know in advance when you enter javascript to an 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.

Consider this example:

<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 alert box to pop up on the screen. The visitor will need to click the "OK" button in the alert box 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 in both the <head> and <body> sections of the document.
In general however, it is advisable to keep as much as possible in the <head> section.

THE FIRST SCRIPT


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:


For instance, one javascript command is called onMouseOver.
If you typed
Onmouseover instead, you might as well have typed qwHETweriuh since javascript just doesn't understand it.
Incorrect capitalization is probably the most common source of error for javascript programmers on all levels!!




Now consider this example:

Instead of having javascript write something in a popup box we could have it write directly into the document.

<html>
<head>
<title>My Javascript Page</title>
</head>

<body>
<script>
document.write("Welcome to my world!!!");
</script>

</body>
</html>



The document.write is a javascript command telling the browser that what follows within the parentheses is to be written into the document.

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

The script in the example would produce this output on
your page:

Welcome to my world!!!






Consider this example to learn where javascript writes the text:

<html>
<head>
<title>My Javascript Page</title>
</head>

<body>
Hello!!!<br>
<script>
document.write("Welcome to my world!!!<br>");
</script>

Enjoy your stay...<br>
</body>
</html>



The output from this example would look like this:

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



As you can see, javascript simply writes the text to where the script is placed within the HTML codes.

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

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

 
CAPITAL LETTERS


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

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

Consider these examples:

Example 1

Example 2

<html>
<head>
<title>My Page</title>
</head>
<body>
<script>
myvalue=2;
myvalue=5;
result=myvalue+myvalue;

document.write(result);
</script>
</body>
</html>

<html>
<head>
<title>My Page</title>
</head>
<body>
<script>
myvalue=2;
MyValue=5;
result=myvalue+MyValue;

document.write(result);
</script>
</body>
</html>



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

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




The best advice is to use the same syntax on all variables.

Either write all variables in small letters, start with one capital letter or write all variables in capitals.

Which syntax you chose is not important
- as long as you chose just one!
 

POP UP BOXES


It is possible to make three different kinds of popup windows.

Try clicking the buttons below to see the differences:


              
 

 

 




ALERT BOX

The syntax for an alert box is: alert("yourtext");

The user will need to click "OK" to proceed.

Typical use is when you want to make sure information comes through to the user.

Examples could be warnings of any kind.
(Typical examples are "Adult Content", or technical matters like "This site requires Shockwave Flash plug-in").




CONFIRM BOX:

The syntax for a confirm box is: confirm("yourtext");

The user needs to click either "OK" or "Cancel" to proceed.

Typical use is when you want the user to verify or accept something.

Examples could be age verification like "Confirm that you are at least 57 years old" or technical matters like "Do you have a plug-in for Shockwave Flash?"

- If the user clicks "OK", the box returns the value true.
- If the user clicks "Cancel", the box returns the value
false.

if (confirm("Do you agree")) {alert("You agree")}
else{alert ("
You do not agree")};



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




PROMPT BOX:

The prompt box syntax is: prompt("yourtext","defaultvalue");

The user must click either "OK" or "Cancel" to proceed after entering the text.

Typical use is when the user should input a value before entering the page.

Examples could be entering user's name to be stored in a cookie or entering a password or code of some kind.

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

Since you usually want to use the input from the prompt box for some purpose it is normal to store the input in a variable, as shown in this example:

username=prompt("Please enter your name","Enter your name here");

 

 

 

VARIABLES


Variables can be compared to small boxes with names.

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.


A variable is simply a place in the computer's memory to store information. All variables are referred to by the unique name you assigned to them.




Consider this example:

<html>
<head>
<title>My Javascript Page</title>
</head>

<body>
<script>
myname="Henrik";
document.write(myname);

</script>
</body>
</html>



This example would write "Henrik" in the document.

Note that when you want text to be stored in a variable you need to put the text in " ".
The reason is that javascript uses " " to tell the difference between text and variables.

Look at this example to see the importance of this.

<html>
<head>
<title>My Javascript Page</title>
</head>

<body>
<script>
Henrik="my first name";
myname=Henrik;
document.write(myname);

</script>
</body>
</html>




Try to predict the output of the example before reading on.

- In the first line, the text "my first name" is stored in the Henrik variable.

- In the second line, the Henrik variable is stored in the myname variable.

- Finally in line 3, the myname variable is written to the document.

The result is that "my first name" will be written on the page.




ASSIGNING VALUES TO VARIABLES

The most common way to assign a value to a variable is using the equals sign.

Consider these examples to see the different ways variables can be assigned to contain either values or text.
Note in particular how parentheses can be used to control how complex formulas are handled.

Example

Resulting value

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

a=2
a=3    (2+1)
a=1    (2-1)
c=5    (2+3)
d=8    (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 type a=a+1;.

Operator

Explanation

Example

++

increment

a=5;
a++;

a would now equal 6

--

decrement

a=5;
a--;

a would now equal 4

%

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

a=8 % 3;
a would now equal 2,
since 8 can be divided
by 3 two times leaving
a remainder of 2.






COMPARING VARIABLES

There are several different ways to compare variables.

The simplest is comparing for equality, which is done using a double equals sign:

if (a==b) {alert("a equals b")};

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

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

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

An example of the error:

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

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




This table contains the different comparing operators:

Operator

Explanation

Example

==

equal to

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

!=

not equal to

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

<

less than

4<5 (true)
5<5 (false)
5<4 (false)

>

greater than

4>5 (false)
5>5 (false)
5>4 (true)

<=

less 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)






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


Sometimes javascript requires the ability to make distinctions between different possibilities.

For example, you might have a script that checks which browser the user arrives with. If it's MSIE, a page specifically designed for that browser should be loaded, if it's Netscape another page should be loaded.




The general syntax for if statements is:

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

An example could be:

if (browser=="MSIE") {alert("You are using MSIE")}
else {
alert("You are using Netscape")};



Again it is important to note that if is written as "if".
Using the capital "IF" would cause an error.

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

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

When you write browser=="MSIE" javascript knows that you want it to compare rather than assign a value.

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




More complex if statements can be made by simply entering new if statements in the else part:

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

An example:

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






AND, OR & NOT

To further enhance your if statements you can use the so-called logical operators.

And is written as && and is used when you want to check if more than one condition is true.

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

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

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






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

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

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

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






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

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

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

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

 

 

FUNCTIONS


Instead of just adding your javascript to the page and having 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 event.

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

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

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

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

<html>
<head>
<script>
function myfunction()
{
alert("Welcome to my world!!");
}

</script>
</head>

<body>
<form name="myform">
<input type="button" value="Hit me"
onClick="myfunction()">
</form>
</body>
</html>



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

 




If the line: alert("Welcome to my world!!"); had not been written within a function, it would simply be performed as soon as the line was loaded.

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




The call of the function is in this line:

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



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

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




The general syntax for a function is:

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

// Here goes the javascript lines for the function
}




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




A typical bug when entering javascript functions is to forget about the importance of capitals in javascript. The word function must be spelled exactly as function. Function or FUNCTION would cause an error.

Furthermore, use of capitals matters in the name of the function as well. If you had a function called myfunction() it would cause an error if you referred to it as Myfunction(), 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.

The following are the most important events recognized by javascript:

Event

Detected when

HTML tags

onFocus=""

Form field gets focus

select, text, textarea

onBlur=""

Form field looses focus

select, text, textarea

onChange=""

Content of a field changes

select, text, textarea

onSelect=""

Text is selected

text, textarea

onMouseOver=""

Mouse moves over a link

A

onMouseOut=""

Mouse moves out of a link

A

onClick=""

Mouse clicks an object

A, button, checkbox,
radio, reset, submit

onLoad=""

Page is finished loading

body, frameset

onUnload=""

Browser opens new document

body, frameset

onSubmit=""

Submit button is clicked

form



Events are used for two main purposes:


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




onFocus, onBlur and onChange are mainly used in combination with validation of form fields.

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

You would then use the onChange event to call the function whenever the user changes the content of the field:

<input type="text" size="20" onChange="validateEmail()">;



Click here to learn more about forms.
Click here to learn more about form field validation.




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

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

Click here to learn more about setting cookies.
Click here to learn more about popup boxes.

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




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


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

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

This can be done using the onSubmit event.


Assume you made a function named checkform() that would validate entries to a form.

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

What you should do, is: add an onSubmit event to the <form> tag this way:

<form method="yourchoice" action="yourchoice" onSubmit="return checkform()">



The function checkform() returns either true or false.
If it returns
true the submit will take place.
If it returns
false the submit will be cancelled.

Click here to learn more about forms.
Click here to learn more about form validation.




onMouseOver and onMouseOut are mainly used for one purpose: To create animated buttons.

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

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

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



The HTML from the example:

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



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

 

 

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.
For example if you wanted it to create exactly 50 lines.

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

Below is a description of each of these two loops:




FOR LOOPS:

SYNTAX:

for (variable=startvalue; variable<=endvalue; variable=variable+incrementfactor)
{

// Here goes the script lines you want to loop.
}



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

Note: The incrementfactor could be negative if you wanted.
Furthermore the
<= could be any comparing statement, ex. >, == or whatever.

EXAMPLE:

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

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

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



Click here to see the page from this example.




WHILE LOOPS:

SYNTAX:

while (variable<=endvalue)
{

// Here goes the script lines you want to loop.
}



Enter a variablename where it says variable.
Enter the
endvalue of the loop where it says endvalue.

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

EXAMPLE:

<html>
<head>
<title>Celsius-Fahrenheit converter</title>
</head>

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

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



Click here to see the page from this example.




BREAK & CONTINUE

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

break simply breaks the loop and continues with what might follow after the loop.

An example would be if you had a loop calculate the squareroot of numbers decrementing from 50.

Since calculating the square root of a negative number is an illegal mathemathic operation you would like the loop to end when the square root of zero had been calculated.

To do this you would add this inside your loop:

if (value==0) {break};






continue breaks the current loop and continues with the next value.

An example would be if you had a loop that divided a certain value with a factor of numbers ranging from -50 to +50.

Since division by zero is an illegal mathemathic procedure the loop would look like this:

for (value=-50; value<=50; value=value+1)
{
if (value==0) {
continue};
document.write((100/value)+"<br>");
}

 

 

ARRAYS


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 automate the process.

Consider this example:

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.




An array must be defined before referring to any of the
variables in it.

This is done using the syntax: variablename=new Array;

Replace variblename with the desired name of your array.

Note: new must be written in small letters and Array must start with a capital A.




As the example indicated, arrays become extremely powerful when used in combination with loops.

However, you don't have to handle array variables in loops.

Single variables can be addressed with a syntax like this:

value[9]=170;






Congratulations!

You have reached the end of the tutorial!

When you feel comfortable with the basic javascript explained
in this section you should continue by learning about the
javascript objects.

Objects are predefined functions for maths, text variables, browser controlling, etc.

As a matter of fact each and every item placed on a webpage is an object that can be changed, read, or written to by javascript.

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