JavaScript Quick Tutorial

Zahid Ghadialy
May 2002

JavaScript

 

JavaScript helps to provide interactivity in the HTML documents.

 

JavaScript could be understood with the simple example below:

 

Example 1:

<html>

<head>

<title>Example 1</title>

<script language="JavaScript">

 

<!-- Hide JavaScript from browsers that don’t understand

 

/* This is a comment and will not be seen on browser.

This comment can be split on multiple lines */

 

// This is single line comment.

 

alert("This is example 1");

 

// End hiding here -->

</script>

<head>

<body>

Just an example

</body>

</html>

 

Before we begin JavaScript in details we should understand the usage of forms.

 

Forms:

Forms are tools in HTML that allow having interactivity in a document. The example of forms could be Pull Down Menu’s, List Selection, Check Box, Radio Buttons, Text Areas, etc. Lets consider a form for simple Pull Down Menu

 

Pull Down Menu Example:

<html>

<head>

<title>Forms Example 1</title>

</head>

<body>

<form>

<select>

<option>Apple

<option>Banana

<option>Grapes

<option>Mango

</select>

</form>

</body>

</html>

 

This example will give a Pull down menu with options of Apple, Banana, Grape and Mango.

 

Taking the same example above, we can use for scrolling menu. The main difference in scrolling menu is to say select multiple instead of select as in above case.

 

Scrolling Menu Example:

<html>

<head>

<title>Forms Example 1</title>

</head>

<body>

<form>

<select multiple=4>

<option>Apple

<option>Banana

<option>Grapes

<option>Mango

<option>Papaya

<option>Orange

</select>

</form>

</body>

</html>

 

The next type of forms is the checkbox. Lets take an example in which we create 3 checkbox’s. Of them 2 are unchecked and 1 is checked.

 

Checkbox example:

<html>

<head>

<title>Forms Example 2</title>

</head>

<body>

<form>

<h3>Fruits</h3>

<input type="checkbox">Apple<br>

<input type="checkbox">Banana<br>

<input type="checkbox" checked>Orange<br>

</form>

</body>

</html>

 

The example above can be converted for Radio Buttons

 

Radio Buttons Example:

<html>

<head>

<title>Forms Example 2</title>

</head>

<body>

<form>

<h3>Fruits</h3>

<input type="radio">Apple<br>

<input type="radio">Banana<br>

<input type="radio" checked>Orange<br>

</form>

</body>

</html>

 

If you try this example out on the browser, you will find that it is not working, as you would have thought. This is because in the above example each Radio Button works individually. This will mean that if the initial value was unchecked then it will remain unchecked and if the initial value was checked then it will remain checked. To make them work together we modify the previous example as follows:

 

Modified Radio Button Example:

<html>

<head>

<title>Forms Example 2</title>

</head>

<body>

<form>

<h3>Fruits</h3>

<input type="radio" name=group1>Apple<br>

<input type="radio" name=group1>Banana<br>

<input type="radio" name=group1 checked>Orange<br>

</form>

</body>

</html>

 

The next type of form would be textbox. The textbox allows us to define a box of particular length and predefined value. Consider the example below:

 

Textbox with Initial value Example:

<html>

<head>

<title>Forms Example 3</title>

</head>

<body>

<form>

An Apple a day keeps <input type="text" size=10 value="Doctor"> Away.

</form>

</body>

</html>

An advanced form of Textbox is the TextArea. Consider the example below:

 

Textarea Example:

<html>

<head>

<title>Forms Example 3</title>

</head>

<body>

<form>

<textarea cols=25 rows=6>

</textarea>

</form>

</body>

</html>

 

The next types of forms are the Submit and Reset buttons. Lets consider their examples:

 

Reset Button Example:

<html>

<head>

<title>Forms Example 4</title>

</head>

<body>

<form>

<input name=text1 value="Name">

<input name=text2 value="Surname">

<input type=Reset value="Initialise Fields">

</form>

</body>

</html>

 

The Reset button is used to initialise the fields to default value. On the other hand the Submit button is used to send the information entered to some web page or website.

 

Event:

Whenever there is any kind of activity on a web browser, an event is generated. Whenever mouse enters a text area or clicks a link or goes over a link an event is generated. Similarly if a keyboard performs some activity on the web browser again event is generated. We will check an example of event that occurs when the mouse goes over a link.

 

OnMouseOver Event:

<html>

<head>

<title>Example 2</title>

</head>

<body>

<form name="form1">

<input type="text" name="text1" value="Do you like Apples?">

</form>

<br><br>

<h3>

<a href="#" onMouseOver="window.document.form1.text1.value='Apples are

Sweet';">Yes</a>

<a href="#" onMouseOver="window.document.form1.text1.value='An Apple a Day keeps Doctors Away';">No</a>

</h3>

</body>

</html>

 

 

Example Script:

Lets take an example where we can actually implement what we have learnt and also feel more power of JavaScript.

 

Complex Example:

<html>

<head>

<title>Example 3</title>

<script language="JavaScript">

function calc()

{

 var x="You asked for ";

 var y=false;

 if (window.document.form1.apple.checked==true)

 {

  x=x+ "Apples";

  y=true;

 }

 if (window.document.form1.banana.checked==true)

 {

  if (y==true)

   x=x+", ";

  else

   y=true;

  x=x+ "Bananas";

 }

 if (window.document.form1.orange.checked==true)

 {

  if (y==true)

   x=x+", ";

  else

   y=true;

  x=x+ "Oranges";

 }

 if (y==true)

  alert(x);

 else

  alert("You asked for nothing");

}

</script>

</head>

<body>

<form name=form1>

<h3>Fruits</h3>

<input type="checkbox" name=apple>Apple<br>

<input type="checkbox" name=banana>Banana<br>

<input type="checkbox" name=orange>Orange<br>

<br><br>

<input type=button value="Submit Order" onclick=calc()>

</form>

</body>

</html>

 

In the above example we can learn more about JavaScript forms, variables, functions, strings, if-else statement, Boolean operations.

 

Variables:

Variables are the way in which JavaScript can store information. Variables must begin will an alphabet or an “_”. The variables are case sensitive, so apple and Apple would be considered as two different variables.The variables begin with the word “var” and all the statements terminate with “;”.

var q=2;

var p=q+11;

Here q is the variable that stores 2. The variable p adds 11 to variable q and stores the value 13 in itself. The variable q will remain unaltered and still hold 2. Variables can also be used to hold strings. For example:

var name= “Zahid”;

Here the variable name will have value Zahid.

 

Strings:

Any collection of alphanumeric characters within “” denotes strings. In the previous example we saw that in variable x, depending on the decision we used to add strings. Since in JavaScript strings are defined as objects we can add them together directly. Lets consider adding two variables.

 

Adding 2 variables Example:

<html>

<head><title>Example 8</title>

<script language="JavaScript">

var a=50;

var b=20;

var c=a+b;

document.writeln(c);

</script>

</head>

<body>

</body>

</html>

 

The answer in the above example is ‘70’. Actually we wanted an output of ’50 20’. To get this result we will need to modify this statement

var c=a.toString()+b.toString();

Actually we can also do the following to get the desired result.

var c=a.toString()+b;

 

Please note that the function toString() has to be written exactly the same way, else JavaScript will not recognise it.

 

There are other functions associated with the string. Lets consider another example.

 

indexOf and lastIndexOf functions example:

<html>

<head><title>Example 9</title>

<script language="JavaScript">

<!--

var str="The cat and the bat ran away with the ball";

var ind=str.indexOf("the");

document.writeln("The index of 'the' = "+ind+"<br>");

var lind=str.lastIndexOf("the");

document.writeln("The last index of 'the' = "+lind+"<br>");

-->

</script>

</head>

<body>

</body>

</html>

 

If the string we are searching is not present then the ‘indexOf’ will return –1. Consider an Email checking example below.

 

<HTML>

<HEAD><TITLE>String.indexOf Example</TITLE>

</HEAD>

<BODY>

<SCRIPT LANGUAGE="JavaScript">

  str_email = prompt("Enter an email address", "");

  if(str_email.length==0) {

    alert("You entered nothing!");

  }

  else if(str_email.indexOf("@")==-1) {

    alert("Your email address does not contain @");

  } else {

    document.write("The @ symbol occurs at index " + str_email.indexOf("@"));

    document.write(" in: <BR>" + str_email);

  }

</SCRIPT>

</BODY>

</HTML>

 

Lets consider a Rolling Text Example script

 

<html>

<head><title>Example 10</title>

<script language="JavaScript">

<!-- Hide from old browsers

var scrollMsg = "Welcome to Zahid's Amazing Homepage";

var msgSpace = "    ";

var beginPos = 0;

function scrollingMsg()

{

 

document.msgForm.stage.value=scrollMsg.substring(beginPos,scrollMsg.length)+msgSp

ace+scrollMsg.substring(0,beginPos);

beginPos=beginPos + 1;

if (beginPos > scrollMsg.length)

   beginPos = 0;

window.setTimeout("scrollingMsg()",100);

}

// End hiding -->

</script>

</head>

<body onload=scrollingMsg()>

<CENTER><!-- put scrolling message onto the form -->

<FORM name=msgForm><INPUT name=stage style="color=red" size=23>

</FORM>

</CENTER>

</body>

</html>

 

Prompt:

Another type of input we use in JavaScript is the prompt. Consider the example below.

 

Prompt Example:

<html>

<head><title>Example 4</title>

<script language="JavaScript">

var name = prompt("Enter your name", "Zahid");

if (name=="")

            name="Stranger";

</script>

</head>

<body>

<center>

<h2>Welcome

<script language="JavaScript">

document.writeln(name);

</script>

</h2>

</center>

</body>

</html>

 

 

Fruit Store Calculator:

Lets develop a calculator for a fruit store that will allow us to compute how much a customer has to pay. The customer selects the type of fruits and the quantity of those fruits and the total amount is output to him.

 

<html>

<head>

<title>Example 3</title>

<script language="JavaScript">

var amount=0;

function calc()

{

 amount=0;

 var x="You asked for ";

 var y=false;

 if (window.document.form1.apple.checked==true)

 {

  x=x+ "Apples";

  amount= amount + 0.2*window.document.form1.apple1.value;

  y=true;

 }

 if (window.document.form1.banana.checked==true)

 {

  if (y==true)

   x=x+", ";

  else

   y=true;

  x=x+ "Bananas";

  amount = amount + 0.1 * window.document.form1.banana1.value;

 }

 if (window.document.form1.orange.checked==true)

 {

  if (y==true)

   x=x+", ";

  else

   y=true;

  x=x+ "Oranges";

  amount=amount + 0.3*window.document.form1.orange1.value;

 }

 if (y==true)

  alert(x);

 else

  alert("You asked for nothing");

 window.document.form1.amount1.value = amount;

}

</script>

</head>

<body>

<form name=form1>

<h3>Fruits</h3>

<input type="checkbox" name=apple>Apple @ 0.2£, quantity

<input type="text" name=apple1 size=5 value="0"><br>

<input type="checkbox" name=banana>Banana @ 0.1£, quantity

<input type="text" name=banana1 size=5 value="0"><br>

<input type="checkbox" name=orange>Orange @ 0.3£, quantity

<input type="text" name=orange1 size=5 value="0"><br>

<br><br>

<input type=button value="Submit Order" onclick=calc()>

<br><br>

<h3>

<p>The total amount is

<input type="text" name=amount1 size=10 value="0">£

</h3>

</form>

</body>

</html>

 

Arrays:

Lets learn a bit about declaring and handling Arrays. JavaScript does not have a simple data type that allows managing arrays. Instead the Arrays are implemented as objects. Arrays could be defined in the following ways:

new  Array();  // An array without specifying the size

new Array(size);  // An array with the size

new Array(element1, element2, element3); // An array with three elements

 

Lets take an array example and try to learn from that.

 

Array Example:

<html>

<head><title>Example 6</title>

</head>

<script language="JavaScript">

var arr = new Array(4);

document.write("<br>Size of 'arr' : "+arr.length);

for(i=0;i<arr.length;i++) {

   document.write("<br>element "+i+": "+arr[i]);

}

arr[0]=55;

arr[1]="Zahid";

arr[2]=true;

arr[3]=3.1415;

arr[4]=0;

arr[7]="I love Fruits";

document.write("<br>Size of 'arr' : "+arr.length);

for(i=0;i<arr.length;i++) {

   document.write("<br>element "+i+": "+arr[i]);

}

</script>

<body>

</body>

</html>

 

From this example we can learn the following things:

·        The first element of an array has index 0. Consequently the last element will be size-1.

·        When an element of an array is empty or if we have not assigned any value to the array element then by default it is undefined.

·        When an array is created we have to use the keyword new to make JavaScript understand how many spaces to reserve.

·        When an element of an array has to be accessed then the element number should be specified between [ ].

·        An array can have mixed data types like integer, boolean, float, string, etc.

·        If the size of the array specified is exceeded then JavaScript will automatically adjust the size of the array.

 

Cookies:

Cookies are little bits of information that you can leave on a user's hard drive, where they stay even after the user leaves your site or turns off the computer, which is extremely useful when you want to remember information about repeat visitors. Some rules must be remembered about the cookies

 

·        Not everyone has a cookie-friendly browser (but most do).

·        Not everyone who has a cookie-friendly browser will accept your cookies (but most will).

·        Each domain is allotted only 20 cookies, so use them sparingly.

·        Cookies must be no larger than 4 KB. That's just over 4,000 characters, which is plenty.

 

Lets consider an example to set the cookie

 

Cookie Setting example:

<html>

<head><title>Example 7</title>

<script language="JavaScript">

<!-- Hide me

function setCookie()

{

  var the_name = prompt("What's your name?","");

  var the_cookie = "wm_javascript=" + escape("username:" + the_name);

  var the_date = new Date("December 31, 2050");

  var the_cookie_date = the_date.toGMTString();

  the_cookie = the_cookie + ";expires=" + the_cookie_date;

  document.cookie = the_cookie;

  alert("Thanks, now go to the next page.");

}

 

function readCookie()

{

  var the_cookie = document.cookie;

  var the_cookie = unescape(the_cookie);

  var broken_cookie = the_cookie.split(":");

  var the_name = broken_cookie[1];

  alert("Your name is: " + the_name);

}

 

// -->

</script>

</head>

<body>

 

<p><b>This page will let you set a Name Cookie. Once the cookie is set then we can read the

cookie. Open this HTMl document from different browser and check the cookie that has been set.

<br><br>

 

<a href="#" onClick="setCookie(); return false;">Set a name cookie.</a>

<br><br>

 

<a href="#" onClick="readCookie(); return false;">Read the name cookie</a>

 

</body>

</html>

 

From the example above we can summarise our learning

·        Setting of cookie is done by document.cookie property. The same property is used to extract the cookie value from the hard disk.

·        Cookie values must never have spaces, commas or semicolons. Since it is difficult for the user to make sure these are not included in the cokkie values, a function called escape() is provided in JavaScript that will remove them. For example we entered the name as Cameron Diaz, then it will be stored as username%3Acameron%20Diaz. The escape() function will convert : to %3A and space to %20.

·        The unescape() function will perform the opposite of escape() function.

·        The function .split(:) (Implying split on colon), will split the the_cookie into 2 parts like an array and store it in broken_cookie. The broken_cookie[0] will have the string “username” and broken_cookie[1] will have the “name entered while storing the cookie”.

 

Frames and Framesets:

Lets consider a Frameset example in which we have 2 frames. Whatever we type in the first frame can be send to the second frame when Send button is checked. Since this is a frameset example, we will need 3 files.

 

File: FrameSet.html

<html>

<head><title>Frames Example 1</title>

</head>

<frameset cols="40%,*%">

   <frame src="Frame1.html" name="frame1">

   <frame src="Frame2.html" name="frame2">

</frameset>

</html>

 

File: Frame1.html

<html>

<head>

<script language="JavaScript">

<!--

function display(forma)

{

 parent.frame2.document.form2.text2.value=forma.text1.value;

}

//-->

</script>

</head>

<body>

Enter a value and then click "Send" Button

<form name="form1">

  <input type=text name=text1><br>

  <input type=button value="Send" onClick=display(this.form);>

</form>

</body>

</html>

 

File Frame2.html

<html>

<head></head>

<body>

<form name="form2">

  Value Received:<br>

  <input type="text" name="text2">

</form>

</body>

</html>

 

 

 


Further Reading

 

·        http://hotwired.lycos.com/webmonkey/programming/javascript/tutorials/tutorial1.html - Thau’s Javascript tutorial

·        http://hotwired.lycos.com/webmonkey/html/97/06/index2a.html?collection=html - Forms Tutorial

·        http://www.iota-six.co.uk/javascript/ - Advanced JavaScript Tutorial

·        Book: JavaScript and VBScript – Benjamin Aumaille

·        http://javascript.internet.com/ - Free JavaScript scripts, tutorials, resources, etc.

·        http://www.javascriptkit.com/ - More JavaScript examples

 

 





Back


HOME



About Us Careers Contribute Advertise






Copyright ©2004-2013 3G4G.CO.UK. All rights reserved.
Contact zahidtg(at)yahoo(dot)com for further information