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=""