Javascript tutorial

Ranveer Singh arya
Arya 1/1/2009

JavaScript Tutorial
Online JavaScript Tutorial
This online Javascript tutorial been very well received judging by the number of emails I get. JavaScript is a vast language and it is not possible to teach everything in these 35 tutorial sessions, however, we will cover most of the basics - statements commands and functions. This Javascript tutorial was written for someone who has no programming experience. I had taken off this tutorial for a little while simply to correct errors, however, if you do find some, please report them here; and if you simply like this javascript tutorial, please do let me know.

JavaScript History
Web pages made using only HTML are somewhat static with no interactivity and negligible user involvement. Interactive pages can be described as those that understand and process user behavior (actions) like mouse movements, mouse button clicks, HTML button clicks etc. HTML tags are just instructions on document layout and structure; the display of the document in the window is dependent on the browser. Interactive pages cannot be built with only HTML, we need a programming language. Further, since the response time to user actions should be quick, the programming language has to be embedded in the browser itself. (Programs residing on servers can not bring about interactivity due to the time taken for sending the user input and receiving the response.) Keeping these things in mind, the people at Netscape came out with a client-side (read browser) language that was integrated with version 2 of Netscape Navigator. They called this language JavaScript. (Actually, JavaScript was initially christened LiveScript. Seeing the popularity gained by Sun Systems' Java, the bigwigs at Netscape changed its name... a clever marketing ploy. Eh?) Microsoft's implementation of JavaScript is called JScript and was first introduced with version 3 of Internet Explorer. JavaScript is thus, a client-side scripting language. There is also a server-side version that is used in Active Server Pages, a technology promoted by Microsoft. This tutorial describes only clientside JavaScript. JavaScript enables browsers to take decisions and process information. This is the key to interactivity.

JavaScript now
At the time of writing, JavaScript is in version 1.2 and is soon to be standardized by the International Standards Organization.

Why do you need JavaScript?

Here are a few things you can do with JavaScript:
      

Validate forms at the client-side saving both the precious server resources and time. Create mouseover effects, change background color of a document with a click of a button... interactivity! Randomly display content without the involvement of server programs. Move HTML elements around pages. Change page contents dynamically. Load content in new browser windows and frames. Make online games.

Nature of JavaScript
JavaScript is based on Object Oriented Programming concept. Its syntax is quite similar to C, C++ and Java. However, it is much easier to learn and implement.

Other Client-side languages like Javascript
VBScript: Implemented only under Internet Explorer, this client-side language is similar to BASIC. It is commonly used in ASP technology. PerlScript: Similar to the Perl Language. Not very well supported by browsers.

What is covered in this Javascript tutorial?
Since this Javascript tutorial was written keeping in mind a novice, we start with the very basics, gently touching JavaScript methods and event handlers and then moving on to variables, loops, functions etc. In the following sessions on this tutorial, you will learn how to detect browsers, print current date and time on a web page, change images on mouse-over, display statements in the browser Status Bar and several other nifty things. Once you get a grasp of these sessions, you can build over what you have learnt through practice and consulting a JavaScript reference.
             

Embedding JavaScript in HTML - Online JavaScript lessons for Beginners Creating your first JavaScript - Javascript basics JavaScript Introduction - Writing JavaScript with HTML JavaScript Guide - Object Oriented Programming in JavaScript Understanding JavaScript objects - Online JavaScript help Online JavaScript Guide - Methods JavaScript Online Reference - alert() method JavaScript Online Help - Event Handlers 1 JavaScript Event Handlers - onmouseover and onmouseout JavaScript Event Handlers - onclick and ondblclick Creating or Opening New Windows (pop-up) in JavaScript JavaScript Functions - Creating and Using - 1 Learning JavaScript Programming - Variables Learning JavaScript Functions - 2

                    

JavaScript Operators - String and Arithmetic Operators JavaScript increment and decrement operators - Operator Precedence Online JavaScript Manual - Variables and JavaScript methods JavaScript Errors - Understanding and Correcting JavaScript IF Statement JavaScript IF-ELSE Statement Browser detection through JavaScript - Navigator Object Date and Time in JavaScript JavaScript - Else If The JavaScript prompt - Getting user input Global and Local variables in JavaScript Functions Understanding JavaScript for Loop JavaScript While Loop JavaScript break And continue Statements For Loops Changing Images on Mouseover Using JavaScript JavaScript - Image Change Using Functions Generating Random Numbers in JavaScript JavaScript Arrays - creating and storing values Random Text Display Using JavaScript Random Image Display Using JavaScript JavaScript Programming Tutorial - Last Words

Embedding JavaScript in HTML - Online JavaScript lessons for Beginners
The first Javascript lesson for the beginner
As I mentioned in the introduction, these online javascript lessons have been developed keeping the beginner in mind. Hence we start with the basics - how to embed JavaScript in an HTML document. Since JavaScript started off as a client-side language (it is now extensive used in Microsoft's ASP technology for server-side scripting), we need to understand how we can include it on web pages so that browsers (clients) can read it. JavaScript works with HTML to bring interactivity to otherwise static documents and can be embedded inside HTML documents in three ways:
  

The code is placed between <SCRIPT> - </SCRIPT> tags. Code is included inside an HTML tag. The entire code is placed in another file, which is called through the SRC attribute of the <SCRIPT> tag.

Using the <SCRIPT> tags

JavaScript code is most commonly included between <SCRIPT> - </SCRIPT> tags. For example:

The LANGUAGE attribute explicitly informs the browser that the enclosed code is JavaScript. The TYPE specifies that the code is in TEXT format. The <!-- and //--> are placed around the code and hide it from browsers that do not understand JavaScript. I advise you to always use these "code hiding" tags since their inclusion is harmless; however if you leave them, the document display is completely ruined in non-JavaScript browsers.

JavaScript code inside HTML tags
To make interactive pages you need to catch or recognise user actions (also called events). The events generated by the user may be mouse clicks, mouse movement etc. To capture these events, we employ small JavaScript code that is placed right inside an HTML tag. Such code is called an event handler.
<A HREF="http://www.webdevelopersnotes.com" onmouseover="alert('Go back to Home Page')"> Home Page</A>

Here we have an anchor tag that surrounds some text ('Home page'). Don't worry if you can't understand the code (you are not supposed to at this stage). Just take a note of how the code is embedded inside the anchor tag. onmouseover is an event handler and as its name suggests, it manages a mouse over action. In this case, onmouseover event handler triggers some response whenever the user moves the mouse cursor over the text enclosed between the anchor tags.

Placing JavaScript code in another file
Another common practice is to place the entire JavaScript code in another file. This external file can then be called using the SRC attribute of <SCRIPT> tag.

<!-//--> </SCRIPT>

Note that the external file containing the JavaScript code has .js extension. It is included in the HTML document through the SRC attribute that takes the URL of the file as its value. There are three main advantages in using this technique. Firstly, you don't need to place the code in all HTML documents, secondly, if a change is required you have to modify only one file instead of several and thirdly, it protects (though partly!) precious code. However, the main disadvantage is that the server has to locate and open one more file. Equipped with this basic knowledge, let's move towards creating your first script.

Creating your first JavaScript - Javascript basics
I remember how I started with tennis. My coach handed me a ball and a racket and told me to practice against a wall. The only instruction I got was to hit the ball above the marked line. Learning a programming language is similar to picking up a sport. You arm yourself with a few statements and practice till you get the hang of them. For this reason I have loaded the tutorial with dozens of with examples and assignments; and we have the first one right here.

Printing text with JavaScript
Start a text editor (example, Notepad in Windows) and type the following:
<HTML> <HEAD> <TITLE>My First JavaScript</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT"> <!-document.write("I love JavaScript"); //--> </SCRIPT> </BODY> </HTML>

Save this file with a .html or .htm extension and view it in a browser. You can also click here to know how it looks. (This opens another window)

document.write("I love JavaScript"); is a JavaScript statement. Note the following points:
   

The JavaScript statement is enclosed in the <SCRIPT> and </SCRIPT> tags. The code informs the browser to write some text in the document. In this case, the text to be written is I love JavaScript. The text is enclosed in quotes and placed inside parenthesis. The quotes are NOT written along with the text; they help to signify the beginning and the end of the text. Though, it is not necessary to end JavaScript statements with a semi-colon, its always a good habit. Trust me!

Single and double quotes in JavaScript
You can write the above code with single quotes too and it will give the same result. However, if the text contains double quotes that have to be displayed, you should use single quotes to surround the text as in: document.write('JavaScript is "NOT" Java'); Click here to view the result. Similarly, to display single quotes nested them inside double quotes.

Case-sEnSiTiViTy in JavaScript
Like other languages, JavaScript is case-sensitive. This means that DOCUMENT.WRITE will not work. Also, a=2 is not the same as A=2. Note: Event handlers are not case sensitive.

1. What do you think happens when you use DOCUMENT.WRITE instead of document.write? 2. What will be displayed if you don't enclose the text inside write() with quotes? 3. Write code that prints your name. 4. Write code that displays It's a good day to die. 5. What is the correct JavaScript code for displaying the following? He said, "Welcome to my world."

JavaScript Basics Tutorial - Assignment answers
1. JavaScript is case-sensitive. Thus, using DOCUMENT.WRITE instead of document.write will result in an error. 2. Forgetting to include the quotes results in an error. The text needs to be surrounded by quotes and placed inside parenthesis.
3. 4. 5. 6. 7. <script language="JavaScript" type="text/javascript"> <!-document.write("Your-name-here"); //--> </script>

9. <script language="JavaScript" type="text/javascript"> 10. <!-11. document.write("It's a good day to die"); 12. //--> 13. </script>

15. 16. 17. 18. 19. <script language="JavaScript" type="text/javascript"> <!-document.write('He said, "Welcome to my world."'); //--> </script>

20. Note: The double quotes are surrounded by single quotes.

JavaScript Introduction - Writing JavaScript with HTML
Take a look at the following code:
<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT"> <!-document.write("JavaScript is <B>great</B>."); //--> </SCRIPT>

You'll notice that along with the text I've thrown in the HTML bold tag. HTML tags enclosed in write() are not displayed. The browser interprets these tags accordingly and then prints the result. In our case, the word 'great' is displayed in bold. Click here to view the result. Here is a code that prints text in blue color:

<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT"> <!-document.write('<FONT COLOR="#0000FF">Blue denim</FONT>'); //--> </SCRIPT>

Click here to view the result. Note that I have used single quotes to enclode the text in write(). Why? Because it is my habit to contain HTML attribute values with double quotes. If I had used double quotes to surround both the attribute value and the text in write(), I would have received an error from the JavaScript interpreter. This kind of quote nesting is used often with event handlers and it's important that you remember it. JavaScript allows inclusion of all HTML tags in write(). You can actually build entire HTML documentes starting from <HTML> tag!

1. Using JavaScript, display your name in green color. 2. Now change the code to display your first name in blue and last name in red. 3. Using only write, display
4. JavaScript is truly 5. Amazing.

6. <BOOK> is not an HTML tag and will be ignored by browsers. What do you think will happen if you include this tag in write()?

Possible Answers
1. 2. <script language="JavaScript" type="text/javascript"> 3. <!-4. document.write('<FONT COLOR="#00FF00">Your-name-here</FONT>'); 5. //--> 6. </script> 7. 8. <script language="JavaScript" type="text/javascript"> 9. <!-10. document.write("<FONT COLOR="#0000FF">your-first-name</FONT> <FONT COLOR="#FF0000">your-last-name</FONT>"); 11. //--> 12. </script> 13. 14. <script language="JavaScript" type="text/javascript"> 15. <!-16. document.write("JavaScript is truly<BR><B>Amazing</B>"); 17. //-->

18. </script>

19. No error is generated, however, the tag is ignored by the browser.

JavaScript Guide - Object Oriented Programming in JavaScript
Object Oriented Programming is a relatively new comcept in the computing field. It is supposed to make life simpler and easier for the programmer, however, the newly initiated get confused quickly. I too was disconcerted at the beginning eventhough I had a good programming experience with BASIC and FORTRAN. The concept is actually quite simple and if you read this session well, I assure you that you will soon grasp it. Note: JavaScript is not a true Object Oriented language as C++ or Java but rather an Object Based language.

Its a wild world out there
Before I start describing objects in programming aspect, let's look some pictures.

Here are two ferocious bears and a docile bamboo eating panda. They are animals that we find in a zoo (Its not pleasant to come across the grizzly in the wild)

Are animals objects?
Yes! The Wildlife Foundation might disapprove of this... but then, I guess it's harmless if we just take it as a analogy! We see objects all around us, the chair we sit on, the table on which our computer is placed and even other humans.

Object Properties
To describe a bear or a panda, we specify its characteristics such as color, size, weight, eating habits, the place where its found etc. These are properties of the animal. Polar Bears Color: White Diet: Fish, seals... non-vegetarian Location: The North Tundra Panda

Color: White and Black Diet: Bamboo shoots Location: China

Object Methods
So what are the things a polar bear can do? It eats, runs, swims, hibernates in the winter season etc. A Panda also eats and runs but it can also climbs trees and seldom swims! Such actions are the functions of the animal object. Functions in object programming are called methods. Thus, an object can be anything, a living being, an inanimate item, a city or even an idea. An object is described by its charateristics called properties and can preform certain functions called methods.

JavaScript Objects
Objects in JavaScript are software entities such as the browser window or an HTML document. Let's describe the browser window object and some its properties and methods. A browser window object is created whenever a document is loaded in a browser. Its Properties
   

Width Height Name The URL of the document it displays

Its Methods
  

Open Close Resize

So, you can define a window object with its properties such as width, height, name etc. The behavior of the window can be controlled using its methods such as open, close, resize etc. The document displayed by the browser window object is itself an object with its own properties and methods. Thus, the document object is contained in the window object. Consider an analogy of our galaxy (Milky Way) object that consists of other objects such as our solar system which further contains objects such as the Earth and the Sun. An easy way to describe the Earth to an alien residing in some other galaxy would be: Milky way - Solar System - Earth

Note that the above can also be written as: Universe - Milky Way - Solar System - Earth But since there is only one universe (hope so!), we can leave out the redundant term. Thus, the Milky Way is a parent object to the Solar System which is itself a parent to the Earth. JavaScript uses the period to separate the parent object from its components. Hence, to refer to the document object we use the following notation: window.document A HTML Form called contactform inside the document might be referred as: window.document.contactform For convenience, webdevelopers name HTML elements using the NAME attribute. Thus, a text field named address located in a form named contactform is refered as: window.document.contactform.address or a radio button called answer as: window.document.contactform.answer or text field called name as: window.document.contactform.name As you would have noticed, the 'window' object is the parent to all other objects, so it is not necessary to explicitly specify it.

1. How many parent objects do you find in the following? window.document.myimage 2. What do you think the following refers to? window.document.myform.myaddress.value

Possible Answers
1. There are two parent objects: window object that contains the document. document object that contains myimage. 2. It refers to the value of myaddress contained in myfrom located in an HTML document.

Understanding JavaScript objects - Online JavaScript help

Okay, so we learnt that JavaScript uses a heirarchical dot notation to refer to objects. In addition to the name property, objects can have other properties. For example, an image located in a document is an object and has the following properties:
        

border: value of <IMG> BORDER attribute height: value of HEIGHT attribute width: value of WIDTH attribute src: the URL of the image hspace: value of HSPACE attribute vspace: value of VSPACE attribute complete: determines whether the image has been completely loaded lowsrc: the URL of lower quality image specified through LOWSRC attribute name: the value of NAME attribute (Just to clarify... the name of an image refers to the HTML name attribute and NOT the file name. By the by, you can use the same value in the NAME attribute value and file name.)

To refer to the source of an image named logo we use: document.logo.src Similarly, its width is refered as: document.logo.width Different HTML elements have different properties. For example, a text field form object has the following properties:
   

name: specifies the text field name value: specifies its value (the text contained in the field) defaultValue: determines the default text value type: identifies its type

To set the value of a text field, we use the = (equal too) operator as:
document.contactform.add.value = "Type your address here";

This is a JavaScript statement that instructs the browser to displays the text Type your address here in the text field add.

1. How do you set the URL of an image called myphoto? 2. How would you specify the value of a text field named yourname contained in contactform form?

Possible Answers

1. document.myphoto.src = "url_of_the_image"; as in
document.myphoto.src = "http://www.webdevelopers.com/myphoto.jpg";

or through a relative URL as
document.myphoto.src = "myphoto.jpg";

2. document.contactfrom.yourname.value = "some_text"; as in
document.contactform.yourname.value = "Please type your name here";

Online JavaScript Guide - Methods
Methods define functions performed by an object. Making a reference to an object method is similar to referencing its property. Thus, document.write(); calls the write() method of the document object. Herein lies an important difference in how methods and properties are refered. Methods are always followed by a pair of parenthesis. Some methods take a value part inside the parenthesis. You would know this by now since you have encountered the write() method in the previous sessions. To refresh your memory here is the code again:
document.write("I Love JavaScript");

The text I Love JavaScript is passed as a value to the write() method of the document object. The main function of this method is to take the value and display it in the browser window. Different objects have different methods associated with them. The submit() method of a form object causes the form to be submitted. The log() method of the Math object computes the logarithm of the number supplied. document.myform.submit(); causes myform to be submitted. Math.log(2); computes the logarithm of 2. The number is passed to the method inside the parenthesis and is called the argument. Similarly, in the example before, I Love JavaScript was the argument passed to the write() method.

1. What do you think following methods do? a. Math.tan(3); b. Math.sqrt(4); c. document.write("www.webdevelopersnotes.com"); d. window.close(); e. window.scroll(); 2. Which method is used to open a new document window? (Take a guess!)

Possible Answers
a. b. c. d. e. f. Computes the tangent of 3. Computes the square root of 4. Prints wwww.webdevelopersnotes.com in the document. Closes a window. Causes the window to scroll. To open a new window we call the open() method of the window object as:

g. window.open();

JavaScript Online Reference - alert() method
alert() is a method of the window object. It is employed to display pop-up boxes with some text and a button labeled "OK". Usage of the alert() method is similar to the write() method of the window object. The text placed inside the parenthesis is displayed on the pop-up box.
window.alert("I am an alert box");

Since it's not necessary to specify the window object we can leave it out from the code. Thus, the following code will function equally well as the one above.
alert("I am an alert box");

Why is alert() a method of the window object?
When I first came across alert(), I wondered why it is method of the window object and not of the document. The answer lies in the fact that the document object defines only the space in the browser window where an HTML document is displayed. The window object determines the entire browser area including the title bar, status bar, the buttons etc. The alert box pops up because of the browser and not the HTML document. Write() on the other hand specifies what has to be written inside the HTML space and hence is a method of the document object.

Difference between document.write() and window.document.write()
There is no difference betwen the two. Remember, the window object is the highest level object. It can contain other objects and their methods. Hence, document is a object contained inside the window object; write() is a method of the document object and is thus, specified after the document object. Explicit declaration of the window object is not necessary thus, document.write() works just like window.document.write()

How to write text on multiple lines in an alert box?
We can't use the <BR> tag here, as we did in write(), because alert() is a method of the window object that cannot interpret HTML tags. Instead we use the new line escape character. An escape character consists of a backslash (\) symbol and an alphabet. When preceeded by the backslash, these alphabet assume a special function. Here are some commonly used escapes characters:
       

\n: Inserts a new line and causes the text following it to be placed on that line. \t: Inserts a tab \r: Carriage return \b: Backspace \f: Form feed \': Single quote \": Double quote \\: Backslash

(Note: there are other escape sequences that consist of the backslash and hexadecimal digits. Their use is rare ... atleast I have never used them!)

This looks really messed up. Click here to see the result. You'll notice that new lines have been introduced at each occurence of the \n escape character.

1. Display your name in an alert box. 2. Now change the code so that your first and last names have three blank lines between them. 3. How will you display \a in an alert box? 4. How would you print the following line in an alert box? He said "JavaScript's the best!"

5. Display an alert box that looks like the one below:

Possible Answers
1. alert("your-name");

3. alert("First-name\n\n\n\nLast-name");

4. To insert three blank lines we use the newline escape character 4 times. (The last line is not blank ... it contains your last name). 5. \a is simply displayed as the alphabet "a". In order to display the backslash, we have to precede it with another backslash character.
6. document.write("\\a"); 7. alert("He said \"JavaScript's the best!\"");

8. Note the escaped double quotes.
9. alert("1\n\t2\n\t\t3");

10. \t inserts a tab.

JavaScript Online Help - Event Handlers 1
JavaScript is all about making web pages respond to actions or events. These events can be of two types depending on how they are generated. Actions such as mouse movements or mouse button clicks etc. are brought about by the user while others like page or image loading have lesser user involvement and take place as the document is loaded in the browser window. Playing the interactivity game is not very difficult. Each object has its properties and methods placed at JavaScript's disposal and modifying these properties through JavaScript brings your pages alive. Take the example of a image rollover effect. The logic is quite simple. Whenever the mouse pointer passes over the image the event is captured with the onmouseover event handler that can then change the value of the src property associated with the image object to another URL. Thus, a new image (with a new URL) is loaded in place of the old one.

What are event handlers?
Event handlers are small JavaScript code placed inside an HTML tag. They help in handling (catching) events. Here is the code from session 1:

<A HREF="http://www.webdevelopersnotes.com" onmouseover="alert('Go back to Home Page')"> Home Page</A>

The onmouseover is an event handler associated with the link object. (As far as JavaScript is concerned, any thing placed between the <A> - </A> is a link object). The value of the event handler is a small JavaScript code. Whenever the mouse pointer is moved over the link, this event handler captures the action and instructs the browser to display an alert box. Pass your mouse pointer over the link below to see how it works. Home Page Let's look at another example:
<A HREF="http://www.webdevelopersnotes.com" onmouseover="window.status = ('Go back to Home Page')"> Home Page</A>

Home Page Here the onmouseover event handler modifies the status property of the window object. It directs the browser to print Go back to Home Page on the status bar. Note that in the first example, onmouseover calls the alert method while in the second it modifies a property value. A final example before we proceed to the next session:
<A HREF="http://www.webdevelopersnotes.com" onmouseover="document.bgColor='#EEEECC'"> Home Page</A>

Home Page This time, onmouseover changes the bgColor (background color) property of the document object and sets it to a light grey color.

Possible Answers
1. <A HREF="somelink.html" onmouseover="alert('your-name')">Link</A>

2. Note: The single quotes are nested inside double quotes.
3. <A HREF="somelink.html" onmouseover="document.bgColor='#FF0000'">Change Background color to red</A>

4. Note: bgColor is a property of the document object since it's the document object that controls the background color of the page. The event handler is case insensitive since its a part of the HTML. However, the code is exclusively JavaScript's domain and is sensitive

to case. Thus, bgcolor will not work (and probably throw error under some browsers). The correct usage is bgColor with the capital C.
5. <A HREF="somelink.html" onmouseover="document.bgColor='#FF0000'">Change Background color to red</A> 6. 7. <A HREF="somelink.html" onmouseover="document.bgColor='#FFFFEE'">Change Background color to pale yellow (original color)</A>


JavaScript Event Handlers - onmouseover and onmouseout
More interactivity - making several things happen at the same time
To change both the background color and the status bar message when the mouse pointer is passed over a link, you have to include two JavaScript statements to the same event handler, onmouseover.
<A HREF="http://www.webdevelopersnotes.com/" onmouseover="window.status='Go Back To Home Page'; document.bgColor='#EEEEEE'"> Change the background color and put a message on the status bar </A>

Note: The two JavaScript statements window.status='Go Back To Home Page' and document.bgColor='#EEEEEE' are separated by a semicolon which informs the JavaScript interpreter to treat the two as individual statements. Each of these statements carries an instruction for the interpreter. The first one changes the message on the status bar while the second changes the background color. The statements are executed in the order they appear. You might not notice it with this example as the execution very fast. Change the background color and put a message on the status bar

A similar example is to bring up an alert box and change the background color.
<A HREF="http://www.webdevelopersnotes.com/" onmouseover="window.alert('Go Back To Home Page'); document.bgColor='#EEFFFF'"> Change the background color and bring up an alert box</A>

Change the background color and bring up an alert box When you pass the mouse cursor over the link above, you'll notice that the alert box is displayed first, JavaScript execution is stopped. Once the OK button is clicked the next statement is executed that changes the background color.

Meeting another event handler - onmouseout()
To complement onmouseover, JavaScript provides the onmouseout event handler. It captures the event when the mouse pointer is taken off the link object.
<A HREF="http://www.webdevelopersnotes.com/" onmouseout="document.bgColor='#FFEEEE'"> Changes the background color when the mouse is placed and then taken off the link </A>

Take your mouse pointer gradually over the link and keep it there... nothing happens; however, the moment you take it off, the background color is changed. Changes the background color when the mouse is placed and then taken off the link

Using two event handlers for the same object
Here is an irritating psychedelic (?!) effect:
<A HREF="http://www.webdevelopersnotes.com/" onmouseover="document.bgColor='#FFFF00'" onmouseout="document.bgColor='#FFFFEE'"> Move your mouse over me! </A>

Move your mouse over me! onmouseover changes the background color to a bright yellow while onmouseout changes it back to the original color. (Moving the mouse over the link repeatedly will result in a bad headache!)

I hope by now, you would have got the hang of using event handlers. Let's see if you are able to crack the following exercise:

1. Construct a link that changes the background color to red and displays Dangerous color message in the status bar when the mouse is passed over it. When the mouse is taken off the link the page should return to the original background color. 2. Now change the code so that the message is displayed in an alert box instead of the status bar.

Possible Answers
1. <A HREF="somelink.html" onmouseover="document.bgColor='#FF0000';window.status='Dangerous color'" onmouseout="document.bgColor='#FFFFEE'">Link</A>

2. Check the result: Link
3. <A HREF="somelink.html" onmouseover="document.bgColor='#FF0000';alert('Dangerous color')" onmouseout="document.bgColor='#FFFFEE'">Link</A>

4. Check the result: Link

JavaScript Event Handlers - onclick and ondblclick
When a link is clicked it takes the user to the page specified in the URL of the HREF attribute. To prevent this from happening, use javascript:void(0) as the value of HREF.
<A HREF="javascript:void(0)" onmouseover="document.bgColor='#EEEEEE'"> Dead link</A>


You may wonder why we can't use HREF="" (a blank or no value) instead of HREF="javascript:void(0)". The reason is that a blank or null value for HREF is interpreted as the URL of the directory. Thus, in our case if we use HREF="", the browser actually sees it as http://www.webdevelopersnotes.com/tutorials/javascript/. javascript:void(0) returns (not specifies!) a null value. Hence, whenever a link is clicked no page is loaded.

Mouse clicks and event handlers
So far we have only looked at event handlers that capture mouse movements over a link. JavaScript also provides event handlers for links that understand mouse button clicks; onclick and ondblclick. Their usage is similar to other event handlers.
<A HREF="javascript:void(0)"

onclick="alert('You clicked on the link')"> Dead link</A>

Dead link
<A HREF="javascript:void(0)" ondblclick="alert('You double clicked on the link')"> Double click on me</A>

Double click on me

1. Construct a link that changes the background color to light blue (#99CCFF) when clicked. 2. Change the code so that clicking on the link also displays an alert box. 3. How about a link that changes the background color to red when clicked and back to the original when the mouse pointer is moved off the link? 4. The open() method of the window object is employed to open a new window. Construct a link that opens a new window when clicked.

Possible Answers
1. <A HREF="javascript:void(0)" onclick="document.bgColor='#99CCFF'">Link</A>

2. Check: Link
3. <A HREF="javascript:void(0)" onclick="document.bgColor='#99CCFF';alert('I am an alert box')">Link</A>

4. Check: Link
5. <A HREF="javascript:void(0)" onclick="document.bgColor='#FF0000'" onmouseout="document.bgColor='#FFFFEE'">Link</A>

6. Check: Link
7. <A HREF="javascript:void(0)" onclick="window.open()">Link</A>

8. Check: Link

Creating or Opening New Windows (pop-up) in JavaScript
If you completed the assignments in the previous session you know how to open new windows. Like the alert() method, the open() also takes arguments. When used without any arguments, the new window displayed is blank. Here I tell you how to embellish this new window.

<A HREF="javascript:void(0)" onclick="window.open('welcome.html')"> Open a new window</A>

Open a new window This opens a new window with welcome.html page.

The arguments of JavaScript open()
The open() method takes four arguments:
window.open('URL', 'NAME', 'FEATURES', 'REPLACE')

We have already seen that if we provide the URL of a document through the first argument, it will be loaded in the new window. NAME: specifies a name for the new window that can then be used as value for the TARGET attribute of <A> tags. FEATURES: let you define properties of the window such as width, height, presence or absence of scrollbars, location bar, stauts bar etc. The list of features is quite daunting so we shall go over them gradually. REPLACE: takes a boolean value... we won't bother ourselves with this argument!
<A HREF="javascript:void(0)" onclick="window.open('welcome.html','welcome')"> Open a new window</A>

Open a new window

List of important features
         

height: Specifies height of the window in pixels. width: width of the new window in pixels location: determines the presence of the location bar menubar: menubar scrollbars: scrollbars status: status bar toolbar: toolbar directories: specifies the display of link buttons resizable: determines whether the window can be resized. If it's absent or its value is set 'no', the window does not have resize handles around its border. fullscreen: Specific to the Internet Explorer, it determines whether the window is displayed in the full screen mode.

<A HREF="javascript:void(0)" onclick="window.open('welcome.html', 'welcome','width=300,height=200')"> Open a new window</A>

Open a new window

This opens a new window 300 pixels in width and 200 pixels in height. Pay close attention to how the features are written. The two features (width and height) are enclosed by a pair of quotes without any spaces and there are no quotes surrounding the values. Did you notice something in the new window? It didn't have any scrollbars, location bar, status bar, menubar, toolbar or buttons! We've already seen that the features argument is optional and consists of a comma separated list of features. If this argument is omitted, the new window has all features present in it. However, if atleast one feature is present, the JavaScript interpreter will consider only the ones that appear ignoring the features that are absent. The width and the height take a number (pixels) as value, for other features the value is either a yes or no.
<A HREF="javascript:void(0)" onclick="window.open('welcome.html', 'welcome','width=300,height=200,menubar=yes,status=yes')"> Open a new window</A>

Open a new window

This window has the menu and the status bars. The others are absent since we didn't specify them.
<A HREF="javascript:void(0)" onclick="window.open('welcome.html', 'welcome','width=300,height=200,menubar=yes,status=yes, location=yes,toolbar=yes,scrollbars=yes')"> Open a new window</A>

Open a new window

Our event handler script is becoming unmanageble... it's too long. In the next session we look at JavaScript functions and how they can contain blocks of code that can be used again and again.

But before that, here is a small novelty for Internet Explorer users. The fullscreen feature is specific to this browser and displays the document on the entire screen. A neat effect... sort of! Click on the F11 to remove the full screen display.
<A HREF="javascript:void(0)" onclick="window.open('welcome2.html', 'welcome','fullscreen=yes,scrollbars=yes')"> Open a full screen window</A>

Open a full screen window

1. Write the code for opening a new window with a width of 400 pixels, height 200 pixels, scrollbars, menubars. 2. If the method for opening windows is open(), what do you think will be the method for closing windows? 3. What happens if you open a new window omitting the features argument?

Possible Answers
1. window.open('url','name','width=400,height=200,scrollbars=yes,menubar=yes'); 2. window.close() 3. The new window carries all the features.

JavaScript Functions - Creating and Using 1
Functions pack JavaScript statements in a block that can be used over and over again. Any programming language worth its salt allows coders to define and call functions.

What are javaScript functions? - An example
<SCRIPT LANGUAGE="JavaScript" TYPE="TEXT/JAVASCRIPT"> <!-function alert_box() { alert("I am displayed by a function"); document.bgColor="#EEEEEE"; } //-->


A function consists of the function keyword, the name of the function followed by a pair of parenthesis and lastly, the JavaScript statement/s enclosed by curly braces. You can give any name to the function as long as it is not a JavaScript reserved keyword. (The list of reserved keywords can be found here.) The function name can contain only alphanumeric characters (alphabet and digits) and the underscore. Also, the name cannot begin with a numeral. Some valid function names display_alert_box calculate _make_love_not_war average1 Some invalid function names @whats_up_doc (invalid character) 123calc (function name cannot begin with a numeral) Remember, function names are case sensitive, thus, alert_box is not the same as Alert_box. The function block can contain several JavaScript statements enclosed between the curly braces. The function in itself does not do anything till we call it.

Calling functions
Calling a function is simple. You have to specify its name followed by the pair of parenthesis.
<SCRIPT LANGUAGE="JavaScript" TYPE="TEXT/JAVASCRIPT"> <!-alert_box(); //--> </SCRIPT>

It's good programming practice to place all functions in the HEAD section of the HTML document between the <SCRIPT> - </SCRIPT> tags. Function calls, on the other hand, can occur in any part of the document (where ever they are needed!), even inside event handler code.

Using a function call inside event handler code

The code below, calls the function we defined at the beginning of this session. This time we call it thru the onlclick() event handler.
<A HREF="javascript:void(0)" onclick="alert_box()"> Function called thru an event handler</A>

Here is how it works: Function called thru an event handler You'll notice that a function call looks very similar to calling a method. Now, wasn't that simple?

Opening a new window through a function
In the previous session, our event handler code for opening a new window had become very long. So instead of writing the code in the HTML tag, we shall place it inside a function and call this function from the event handler.
<SCRIPT LANGUAGE="JavaScript" TYPE="TEXT/JAVASCRIPT"> <!-function open_win() { window.open('welcome.html','welcome','width=300,height=200, menubar=yes,status=yes,location=yes, toolbar=yes,scrollbars=yes'); } //--> </SCRIPT>

Note: the entire JavaScript code should be placed on a single line. For clarity, I have put the code on multiple lines. We name this function open_win and place it in the HTML head section.
<A HREF="javascript:void(0)" onclick="open_win()"> Get a welcome message</A>

Get a welcome message

Really appreciating functions
What if you had ten links on a page each opening a new 400X200 pixel window with a different url? Writing separate code for each link can become quite a pain. A simple solution would be to create a function that opens the new window and call it through an event handler. However, we

are still left with a problem! How do we instruct the same function to load a different url in each new window? Before we delve deeper into functions let us have a look at variables.

1. 2. 3. 4.

How many times can you call a function? Can function calls be used in event handler code? Why are the curly braces needed in a function? Why won't the following code work?

5. function 3_alert_box 6. { 7. alert("Hi!, I am from a function'); 8. }

9. Construct a function that brings up an alert box, changes the message on the status bar, changes the background color and opens a new window 300X200 pixels in dimension. 10. Okay, you might not be prepared for this one... but take a guess anyway. Why do functions need a pair of parenthesis?

Possible Answers
1. 2. 3. 4. As many times as you want. Yes! we've already seen this through examples. Curly braces are needed to contain the JavaScript statements forming a block. There are three mistakes in the code a. The function name is invalid. The name cannot begin with a numeral. b. The pair of parenthesis following the name are missing c. In the alert statement, single quotes are used instead of double quotes to close mark the end. 5. The function consists of four JavaScript statements.
6. function some_name() 7. { 8. alert("some_text"); 9. window.status='some_message'; 10. document.bgColor='some_color'; 11. window.open("url","name","width=300,height=200"); 12. }

13. If you remember, the text contained in the alert() method is called an argument. We've passed the url, the name and the features as arguments to the open() method of window object. Similarly, functions can take arguments too. The arguments are supplied as a comma separated list. More on this in later sessions.

Learning JavaScript Programming Variables

Variables are used for storing values. They can be considered as building blocks of a program. JavaScript allows you to store all kinds of values in variables.

What are variables and why have them?
In simplest terms, a variable is a container of values. These values can be changed continually during the script execution. For example, if a variable contains the number 2 as value, we can change it (using operators) to contain something else. Further, we have the convenience of refering to a variable using its name.

Variable names
Once a value is stored in a variable it can be accessed using the variable name. A variable name can consist of alphanumeric characters and the underscore. It cannot begin with a numeral, though. Note that variable names are case sensitive and my_name is not the same as MY_name. Valid variable names my_name invoice2 _total Average Invalid variable names 100_numbers (name starts with a numeral) rate%_of_inflation (non legal character)

JavaScript variable initialization
You'll recall that variables are store houses. In order for them to contain values, each variable is first assigned a memory address. Whenever the JavaScript code requires a variable it refers to this memory address and picks up the variable and its value. The var keyword explicitly associates a variable to a memory address. This process is called initialization.
var your_name; var total;

Here two variables, your_name and total have been initialized. However, no value has been assigned to these variables. The process of initialization just sets a memory location for a variable. You can test for the value of an initialized variable through the alert() method. JavaScript returns the value "undefined".

Click here to test the alert method Note: The variable in the above alert() method is not surrounded by quotes.

Assigning values to variables in JavaScript
JavaScript allows us to initialize as well as assign values to variables in the same statement. To assign a value to a variable we use the equal to (=) sign. Thus,
var url = "http://www.webdevelopersnotes.com/"; sum_total = 2001;

Sets the value of url to http://www.webdevelopersnotes.com/ and sum_total to 2001. The eagle-eyed would have noticed the subtle difference in how the two variables are set. In the first statement, the value part is enclosed in quotes while the quotes are missing in the second statement. The reason is that http://www.webdevelopersnotes.com/ is text while 2001 is a number. [The equal to sign is know as the Assignment operator in JavaScript. It acts on two operands, one on its right and the other on its left. The function of this operator is to assign or change variable values.] When working with JavaScript variables, it's advisable that you initialize them with the var keyword at the very beginning of the script. This will prevent unnecessary errors.

Data types
Variables store data. In JavaScript, this data can be of several types:
    

Number: an integer or a floating-point number. String: Consists of alphabet, numerals or any other characters (even escape characters). Boolean: A logical true or false value. Null: Consists of a value, null. Undefined: Consists os a value, undefined.

Was this confusing? To simplify the explanation, let's look at the first two data types.

Numbers as data types

A number data type can be an integer or a floating-point. Some integer values 4 123 50 72 Some floating-point values 10.34 -467.234 90.00 0.006 3.0e10 6.023e-23 34e1 Are floating-point numbers decimals numbers? Yes (sort of!) What is the e doing in the last three values? e or E is an exponent and is always followed by an integer exponent value. In simple terms it means X 10 interger exponent.
3.0e10 6.023e-23 34e1 means means means 3.0 X 1010 6.023 X 10-23 34 X 101

Thus, floating point numbers can consists of either a decimal number or a very large or small number that is represented using the e notation. Numeric data types can be manipulated using mathematical operators such as addition, subtraction, multiplication etc. We will look at these very shortly.

String Data Type
Any character or sting or characters enclosed in double or single quotes is a string data type. "www.webdevelopersnotes.com" 'manish@webdevelopersnotes.com' "Hello\nWorld" "Gone in 60 seconds" "12345678" So string data can consist solely of numerals? Yes! However, the number behaves as a string data type and not numeric data. For example, "4" + "10" is equal to "410" but 4 + 10 is 14! (Note, the double quotes... more on this later)

Why have so many data types?

Data Types such as string, number etc. have to be treated in a different manner. For example, you can add, subtract, or multiply numbers but multiplying string data (read text) does not make sense. We will look at this in more detail when discussing operators. If you have understood this much, you are ready for the nest session.

1. What's wrong with this statement?
2. 4thhouse = "John Doe";

3. Is "46" a numeric data type or a string?

1. A variable name cannot begin with a numeral. 2. String

Learning JavaScript Functions - 2
Here is how you solve the problem of using the same function to open windows with different urls. Take a good look at the code below:
function open_win(url_add) { window.open(url_add,'welcome', 'width=300,height=200,menubar=yes,status=yes, location=yes,toolbar=yes,scrollbars=yes'); }

The function has a parameter url_add inside the parenthesis. It occurs in the function once again at the place where we specify the URL for the new window, however, this time it's not enclosed in quotes. To call the open_win function, we pass an argument which is the url address of the document we plan to display in the new window.

When open_win is called, we pass the url as an argument. Note that the url is a string data type and has to be enclosed in quotes. The function picks up the argument and puts it in the value of the url_add variable. The variable containing a URL address (welcome.html) and is used inside the function in place of the actual URL string.

<A HREF="javascript:void(0)" onclick="open_win('welcome.html')">Welcome message</A>

Check the result here: Welcome So if we want to open 10 pop-up windows each displaying a different URL, we call the function 10 times, each time using with a different URL as argument. The beauty is that we don't have to write separate functions for displaying pop-up windows with individual URL addresses; the same function is sufficient.

Spicing up this page
I've placed this function in the HTML head.
function change_back(colorval) { document.bgColor=colorval; }

I can then call it from several event handler code, as
<A HREF="javascript:void(0)" onmouseover="change_back('#CCCC99')"> Background Color 1</A>

Each link below, passes a different color code to the function. Move your mouse over the links below to see the effect. Background Color 1 Background Color 2 Background Color 3 Background Color 4 Background Color 5 Background Color 6 Background Color 7 Background Color 8 Background Color 9 Original Color

1. Create a function that loads a new window 300 X 200 pixels in dimensions. 2. Now change the code above so that you can pass the URL as argument to the function

Possible Answers

1. function open_win() 2. { 3. window.open('url','name','width=300,height=200'); 4. }

6. function open_win(doc_url) 7. { 8. window.open(doc_url,'name','width=300,height=200'); 9. }

10. Note: the argument occurs without the quotes

JavaScript Operators - String and Arithmetic Operators
We've already seen how values are assigned to variables. The equal to sign is an assignment operator.
var lucky_number = 7; var url = "http://www.webdevelopersnotes.com";

Operators work on one or more values, called operands to yield a single result. An expression is a combination of operands and operators. In the first example above, the assignment operator (=) sets the value of lucky_number variable to 7. The two values on the left and right hand side of the operator (lucky_number and 7) are, thus, the operands. The full JavaScript statement is an expression.

Arithmetic Operators
Arithmetic operators work on one or more numeric values yielding a single result.
      

+ Addition - Subtraction * Multiplication / Division % Modulus ++ Increment by 1 -- Decrement by 1

var a = 4 + 10;

In the expression above, the addition operator adds 4 and 10 to yield 14 and the assignment operator assigns this value to the variable a.
var b = 3; (variable b is assigned a value of 3) b = 10 + 5 + 3 + 6; (b now equals 24)

var c = 40 - 5; (c = 35)

var d = 100 * 4; (d = 400)

var e = 100 / 4; (e = 25)

Using variables in expressions
Consider the following code
var var var var a b c d = = = = 4; 6; 10; 3;

var e = a + b + c; (e = 20) var f = b - c + a; (f = 0) var g = b / d + b; (g = 8)

What is Modulus?
The JavaScript Modulus Arithmetic operator returns the remainder left after division.

var a = 70 % 16; (a is now equal to 6, since the remainder left after dividing 70 by 16 is 6) var b = 64 % 8; (b equals 0)

What are increment and decrement operators?
These arithmetic operators are used for increasing or decreasing the value of a variable by 1. They are used very frequently in JavaScript for loop and in other routine operations.
var a = 5; a++; var b = 10; b--; (a = 6)

(b = 9)

The function of the increment operator (and the decrement operator) can also be achieved by adding the digit 1 to the variable as:
a = a + 1; OR b = b - 1;

So why use a++ instead of a = a + 1? The reason is that the JavaScript engine does the calculation for increment and decrement operators much faster. The difference in speed is not perceptible for small calculations and loops, however, with thousands of calculations, you'll notice that the processing with the increment or decrement operator is much faster.

Strings and the String Operator
Just like numbers, variables can contain the string data type. Any text has to be stored as strings. Here are a few examples:
var name = "Johnny Bravo"; var url_address = 'http://www.webdevelopersnotes.com/'; var music_piece = "Mozart's Symphony No. 40"; var page_number = "15";

When assigning strings to variables, they have to be surrounded by quotes, single or double. If you forget this, JavaScript will throw an error. Note, even numerical digits can be stored as string data (look at the last example above). In such cases, the number acts as a string data type and NOT as a numeric data type. The following will clear any doubts... To concatenate two strings, you use the + string operator.
var first_name = "Johnny"; var last_name = "Bravo"; var full_name = first_name + last_name; Result: full_name = "JohnnyBravo"; (note, no space)

To introduce a space, we add a space character between the two variables.
full_name = first_name + " " + last_name; Now, full_name = "Johnny Bravo";

Lastly, we look at how JavaScript handles digits as string data.
var page = "15"; var page2 = page + 1; var page3 = page + "2"; Result: page2 = "151"; page3 = "152"; (note the quotes)

The reason is that the variable page stores digits as string data, the + sign, in this case behaves as the string concatenation operator and not as the arithmetic addition operator.

1. What is the advantage of using a++ instead of a = a + 1? 2. What is the value of variable r ?
3. var r = 46 % 7;

4. Final value of variable a at the end of all statements?
5. 6. 7. 8. var var var a = a b c a = = = + 4; 5; 10; c + 6;

9. Which operator is used to concatenate two strings? 10. At the end of all processing, what will variable t contain?
11. 12. 13. 14. 15. 16. var s1 = "Made "; var s2 = "U "; var s3 = "and me"; t = s1 + "4 " + s2 + s3;

Possible Answers
1. Calculations perfomed using the increment or decrement operators are much faster. There is also the ease of use, especially when you learn to use these in for loops. 2. r = 4, because 46 divided by 7 leaves 4 as a remainder. 3. a = 20 4. The + string operator. 5. t = "Made 4 U and Me"

JavaScript increment and decrement operators - Operator Precedence
A note about the increment and decrement operators
Unlike other operators, the increment and decrement operators act on only one operand. They are hence called Unary operators. They can be used either before or after a variable as in:
a++; b--; OR ++a; --b;

When these operators are used as prefixes, JavaScript first adds one to the variable and then returns the value. When used as suffixes, the value is first returned and then the variable is incremented. Let's know more about this:
var a = 5; b = a++;

(b contains the initial value of a, which is 5. a, on the other hand is now equal to 6) var a = 5; c = ++a; (In this case, JavaScript first adds 1 to a, changing its value to 6. This value is returned to c. Thus, c = 6)

Read the section again, if you've not understood this concept.

Operator precedence in JavaScript
Take a look at the following code... what do you think will be the value of variable res?
var res = 25 + 100 * 4;

There are two ways to look at this
 

Start by adding 25 to 100 and then multiplying the result with 4... yields 500. Multiplying 100 by 4 and then adding 25... yields 425.

Let us find out how does JavaScript solve the problem JavaScript has this inbuilt thing called Operator Precedence. It's a list of operators specifying the order in which they will be executed if two or more are found in the same expression. In our case, the multiplication operator has a higher precedence than the addition operator. Hence, JavaScript will first multiply 100 with 4 and add 25 resulting in 425.

Do you need to learn the operator precedence table?
NO! JavaScript expressions (such as the one above) can be made more clear by adding parenthesis. Thus, depending on our need, we can write the statement as:
res = 25 + (100 * 4); OR res = (25 + 100) * 4; res = 500 res = 425

1. Final value of variable total?
2. total = (60 * 5) + ((40 / 8) - 9) - ((4 * 6) / 2);

3. What is the value of variable b?
4. 5. a = 23; b = (++a) + 6;

Possible Answers
1. total = 284 2. b = 30

Online JavaScript Manual - Variables and JavaScript methods
Till now we've looked at two important methods, the alert() method of the window object and write() of document object. You've also seen how text or numbers can be passed to these methods. Let's consider a situation where you plan to display the name of the visitor on the page. To do this you would first have to get the visitor's name (we'll shortly see how to achieve this), store it in a variable and send the result to the document.write() method. Here we'll examine how we can pass variables to JavaScript methods.
document.write("Your name is " + vis_name);

We've assumed that the visitor's name is stored in a variable called vis_name. Note how the variable is written outside the quotes of the write() method. If this variable was included in the quotes, JavaScript would have written vis_name instead of the name of the visitor. Similarly, for the alert() method, we would pass the value as:
alert("Welcome " + vis_name + "\nHow are we today?");

Remember, a variable should be placed outside the quotes to display its value.

1. What do you think will be written on the window by the following code?
2. 3. 4. 6. 7. 8. var url = "http://www.webdevelopersnotes.com/"; document.write("Welcome to <B>" + url + "</B>"); var my_movie = "Godfather"; alert("My favorite movie is my_movie");

5. What will be displayed on the alert box?

9. What is written on the document?
10. 11. 12. 13. var sum_total = 6000; document.write("The total is " + "sum_total");


(Note: sum_total contains numeric data)

15. Write a function that takes your name as argument and displays in an alert box, a personalized welcome message, something like Welcome, Johnny Bravo. 16. Change this function so that it displays the welcome message in the status bar instead of an alert box. (Note: Use window.defaultStatus property of the window object)

Possible Answers
1. Welcome to http://www.webdevelopersnotes.com (The variable lies outside the parenthesis, hence its value is displayed.) 2. My favorite movie is my_movie (JavaScript cannot interprets my_movie as a variable since its enclosed in the quotes. 3. The sum total is sum_total (Variable placed inside quotes. JavaScript makes no discrimination between a string data or numeric data when displaying variable values)
4. 5. function msg(name) 6. { 7. alert("Welcome " + your_name_here); 8. } 9. 10. // Calling the function 11. 12. msg("your_name_here");

14. function msg(name) 15. { 16. window.defaultStatus("Welcome " + your_name_here); 17. } 18. 19. // Calling the function 20. 21. msg("your_name_here"); 22.

23. You might ask why we use defaultStatus instead of simply window.status. The reason is that window.status is associated only with event handlers and cannot recognize a variable even if its outside the quotes.

JavaScript Errors - Understanding and Correcting
A short note about errors before we proceed to the next session. When you are learning a new programming language it takes time to understand its syntax. Your code might have a few bugs; it's okay as long as you know how to correct them.

JavaScript beginners mainly make three kinds of errors

They might try to call a variable that is not yet defined. Solution: Remember to always initialize all variables you expect to use in the script.

Forgetting the starting or ending quote or parenthesis as in a method or function. Solution: Place the opening and ending parenthesis or quotes together, then write the code/text between them.

Using a property or method that does not belong to an object, for example, using document.alert() instead of window.alert(). Solution: You don't have to learn each and every object's properties and methods at the very start... you'll get the hang of it all gradually.

JavaScript IF Statement
The beauty of programs lies in the fact that they are able to take decisions on the basis of information you provide. In all the programming languages I've come across, the If statement is extensively used for this purpose. It's actually quite simple to use the if statement and here is the format of an if statement.
if (condition) { statements to execute }

When JavaScript encounters an if statement, it checks the condition. If and only if, it is found to be true, the statements enclosed within the curly braces are executed. Note, the condition is always enclosed by a pair of parenthesis. Let's look at some examples.
var a = 5; var b = 5; if (a == b) { alert("The two quantities are equal"); }

First, two variables are initialized and assigned the same numeric value (5). The if statement then checks for their equality and pops-up an alert box if the two variables are equal. The == comparison operator does the job of checking the two variables. The other Comparison operators are:
    

!= Not equal to < Less than > Greater than <= Less than or equal to >= Greater than or equal to

The == is a 'Comparison Operator' while = is an 'Assignment Operator'. Be sure to use the comparison operator in a condition. If you use the assignment operator, the code will not function and JavaScript will NOT throw an error... it'll simply reassign the variable on the left.

The 'Confirm' Box
A 'Confirm' box was displayed when you first entered this page. It's brought about by using the confirm() method of the window object, similar to the alert box.
confirm("Did you like the movie 'Godfather'?");

Click here to test a confirm box The confirm box has two buttons, an "OK" and a "Cancel" button. When the user clicks on "OK" the value 'true' is returned, while clicking on "Cancel" returns 'false'. We can capture this returned value in a variable and test it through an if statement. Let's look at a similar real world example:
var response = confirm("Have you understood the confirm box?"); if (response == false) { alert("Go thru the sessions again"); }

Click here to test the code If you click on the "Cancel" button, confirm returns false as value that is stored in the variable response. The if condition then tests this variable. Since the condition is true (response is equal to false), the statements inside if are executed and you get an alert box.

1. To which object does the confirm() method belongs to? 2. What value is returned by a confirm box if a user clicks on the "Cancel" button? 3. In the following code, will the condition in the if statement be true?
4. 5. 6. 7. 8. 9. 11. 12. 13. 14. 15. 16. 17. 18. 20. 21. 22. 23. 24. 25. var a = 6; var b = 10; if (a != b) { statements... } var a = 20; var b = "20"; if (a == b) { alert("They are equal"); } Note: a contains numeric data while b contains string. var get_res = confirm("Did you like this session?"); if (get_res == true) { alert("Okay! Let's proceed to the next"); }

10. Check the code below... will the statements inside if be executed?

19. What happens in the following code?

Possible Answers

1. 2. 3. 4.

The window object. false a and b are not equal, the condition will be TRUE since we are checking for inequality. Yes! the statements will be executed It's rather strange but JavaScript does not differentiate between the two data types with the comparison operator. 5. If the user clicks on the "OK" button, an alert box pops up. Nothing happens if "Cancel" is clicked.

JavaScript IF-ELSE Statement
Each condition has two paths from which we choose one. For example, "If it's raining, I'll stay at home else I'll go out for a stroll." Just like the conditions of everyday life, the conditional if statement in JavaScript has an else clause. It allows us to take the alternate path when the condition in if is false.
if (weather == "raining") { alert("I'll stay at home"); } else { alert("I'll go out for a stroll"); }

We can extend our if statement we met in the previous session to construct a better confirm box.
var response = confirm("Have you understood the confirm box?"); if (response == true) { alert("Okay, let us continue"); } else { alert("Go thru the previous session again"); }

Click here to see how it works.

Note that the statements in the else block are executed ONLY when the condition in if is false. The following code checks if a number is even or odd and displays an appropriate alert box.
var n = "23"; if (n%2)

{ alert("Number is Odd"); } else { alert("Number is even"); }

Click here to see how it works. Conditions in JavaScript can either be true or false. A false condition is one in which the result is zero or null. In the code above, the remainder left after dividing an even number by 2 will be zero (number modulus 2 = 0), hence the condition will evaluate to false. However, if the number is odd, the remainder left after dividing the number by 2 will be 1 and the condition will evaluate to true. Thus, the code block inside else will be executed when the number is even. If this sounds confusing, go through the code and read this section once again.

The NOT operator !
The exclamation mark ! is called the NOT operator. It reverses the return value of a condition. Thus, !(true) is returned as false and !(false) returns true.
var a = 10; if (!(a == 10)) { alert("The magic of JavaScript"); } else { alert("The beauty of JavaScript"); }

In the code above, we assign variable a a value of 10. The if statement checks the value of the variable and displays an alert. So which alert is displayed? Since a is 10, the condition (a = 10) returns true. However, the NOT operator reverses this condition to false, hence the alert in the else block is displayed.

1. What will be displayed by the code below if variable today = "Monday"?
2. 3. 4. 5. 6. 7. if (today == "Sunday") { document.write("Let's go for a movie"); } else {

8. 9. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 22. 23. 24. 25.

document.write("I have tons of work to do"); } var a = 40; var b = 60; if (!(a > b)) { alert("Hello"); } else { alert("Bye"); } if (!(!(true))) { statements ... }

10. What is the output of the following code?

21. What will the following if condition evaluate to?

Possible Answers
1. The condition in if checks if the value of variable today is equal to "Sunday". In our case, this is false, hence the else code block is executed and "I have tons of work to do" is displayed in an alert. 2. Variable a is 40 and b is 60, hence a is less than b. The condition in the inner pair of brackets is thus 'false'. However, the ! operator (also called the NOT operator) changes it to 'true'. The function of the NOT operator is to reverse a condition. An alert box with "Hello" will be printed when this code is executed. 3. The 'true' condition is changed to 'false' by the first NOT operator. It then changes back to 'true' when it encounters the second NOT operator.

Browser detection through JavaScript Navigator Object
Getting client (browser) details is very easy through JavaScript. Client name, version, codename and the platform used are available through the navigator object and its properties. (The navigator object was named after Netscape Navigator).
   

navigator.appName - Gives the name of the browser (application Name) navigator.appVersion - Gives the browser version (application Version) navigator.appCodeName - Gives the browser codename (application CodeName) navigator.platform - Gives the platform on which the browser is running

Because of browser incompatibility issue in DHTML, some web develpers make two versions of their site, one that is compatible with Internet Explorer and the other that contains Netscape

Navigator specific code. These developers use a browser detection script to transfer the visitor to the respective site. We'll concentrate only on Internet Explorer and Netscape Navigator since they are the most prominent browsers on the Internet. To automatically transfer the visitor, we have to take the help of location property of the window object. Let's look at the code.
<SCRIPT LANGUAGE="JavaScript" TYPE="TEXT/JAVASCRIPT"> <!-var bname = navigator.appName; if (bname == "Microsoft Internet Explorer") { window.location="explorer_version.html"; } else { window.location="netscape_version.html"; } //--> </SCRIPT>

Deconstruction of the browser detection script
The browser name is obtained through navigator.appName and is stored in variable bname. Using an if statement we check the value of this variable. If it's "Microsoft Internet Explorer", we transfer the visitor to explorer_version.html else, the visitor is taken to netscape_version.html. Note that window.location takes a URL as value.

1. What is returned by navigator.appName? 2. What is the value taken by the location property of the window object?

Possible Answers
1. The browser name 2. The location property takes a URL as value. This can either be a relative or an absolute URL.

Date and Time in JavaScript

The date object is very useful for obtaining the date and time on the client. It supports various methods, which return a specific value. To start working with dates and time, we first initialize a variable and assign it a value with the new operator and the Date() constructor. The main function of the new operator with Date() constructor is to create a new date object that is stored in the variable. Here is the code:
var d = new Date();

Thus, variable d contains a new date object. We can now call the various methods of this date object.
var var var var var var var t_date = d.getDate(); t_mon = d.getMonth(); t_year = d.getFullYear(); t_hour = d.getHours(); t_min = d.getMinutes(); t_sec = d.getSeconds(); t_mil = d.getMilliseconds; // Returns the day of the month // Returns the month as a digit // Returns 4 digit year // Returns hours // Returns minutes // Returns seocnds // Returns Milliseconds

Now we can easily display the date, month and year in an alert box, using the values stored in respective variables.
alert("Today's date is " + t_date + "-" + t_mon + "-" + t_year);

Click here to display the alert box The eagle-eyed would have noticed that the month digit is one less than the present month. Hence, if you want to display the month, increment the value returned by getMonth() by 1. The corrected code should be:
t_mon++; alert("Today's date is " + t_date + "-" + t_mon + "-" + t_year);

Check the results Similarly, we can get the time using the variables that store hours, minutes, seconds and milliseconds values.
alert("The time is " + t_hour + ":" + t_min + ":" + t_sec);

Get time in an alert box In the next session we'll see how we can display a greeting based on the client time.

1. Which method of the date object is used to get four digit year value? 2. What is the value of variable mon assuming that the present month is March?
3. 4. var t = new Date(); var mon = t.getMonth();

5. The hours are represented in 24 hour clock. If midnight is 0 what is noon?

Possible Answers
1. The getFullYear() method. 2. Variable mon would be 2 since JavaScript returns month values one less than the present month. January is 0, February is 1 and so on till December, which is 11. 3. Noon will be 12.

JavaScript - Else If
We've already learnt that conditions can take one of the possible two paths. That is, when the condition is 'true' the if statement block is executed while the statement block in else is executed when the condition is 'false'. However, as in life, things are rarely black or white... there are always shades of grey. The JavaScript if - else statements also provides for else if clauses through which we can make additional branches to the condition.
if (number > 0) { alert("Number is a positive integer"); } else if (number < 0) { alert("Number is a negative integer"); } else { alert("Number is 0"); }

Note that the else if clause is followed by another condition placed between parenthesis. If this condition is true, the statement inside the else if block are executed. The code above checks the value of variable number. When number is greater than 0, the statements in if block are executed and when number is less than 0, the statements in else if block take over. Finally, if the number is equal to zero, the conditions in if and else if are 'false' and the program execution falls to the statements in else clause block. When you first entered this page, you received a greeting. This greeting is customized according to the time on the client (your) machine. Let's see how it works.
var d = new Date();

var t_hour = d.getHours(); if (t_hour <= 3) { alert("Hello dear visitor,\nWorking late aren't we?"); } else if (t_hour > 3 && t_hour < 12) { alert("Good morning dear visitor"); } else if (t_hour >=12 && t_hour <= 16) { alert("Good afternoon dear visitor"); } else { alert("Good Evening dear visitor"); }

Click here to run the script again We first initialize a variable using the new operator with the Date() contruct. The value of hours is stored in t_hour variable by employing the getHours() method of the date object. The value of t_hour variable is then passed through if-else if-else conditions. Thus, depending on the time of the day (time in hours), a greeting is displayed in an alert box. You'll recall that JavaScript clock is a 24 hour clock.
   

When t_hour is less than equal to 3 (0, 1, 2, or 3): alert box displays "Hello dear visitor,\nWorking late aren't we?". When t_hour is more than 3 AND less than 12: alert box displays "Good morning dear visitor". If the value of t_hour is greater than equal to 12 AND less than equal to 16: "Good afternoon dear visitor" is displayed in the alert box. For all other values of t_hour (17, 18, 19, 20, 21, 22, and 23): alert box displays "Good Evening dear visitor".

You can check this script by changing the time on your machine and clicking on the above link.

The && and || operators
The && (AND) and || (OR) are logical operators. They are used to extend conditions.
if (number > 4) { statements... }

The above condition checks is variable number is greater than 4. To check if this variable value lies between 10 and 4, we employ the && operator.
if (number 7gt; 4 && number < 10) { statements... }

Thus, the statements inside the if block will be executed if number equals 5, 6, 7, 8 or 9. Now, if we want to display an alert box if the value of number variable is less than 20 or more than 50, we use the || operator.
if (number < 20 || number > 50) { alert("..."); }

In the code above, an alert box will be displayed if number is 18, 5, -435, 51, 324... However, if the value of number lies between 20 and 50 (included 20 and 50), no alert box will be displayed.

1. When do you use an else if clause? 2. How many else if clauses can you use in an if condition? 3. Which alert box will be displyed if variable marks is 75?
4. if (marks == 100) 5. { 6. alert("You've touched a century"); 7. } 8. else if (marks >= 80 && marks < 100) 9. { 10. alert("That's good"); 11. } 12. else if (marks >= 60 && marks < 80) 13. { 14. alert("Above average performance"); 15. } 16. else if (marks > 50 && marks < 60) 17. { 18. alert("Average performance"); 19. } 20. else 21. { 22. alert("That's poor performance"); 23. }

Possible Answers

1. An else if clause is used in an if statement when you would like to have more than 2 branches for the condition. 2. You can use any number of else if clauses as long as the conditions associated with each are mutually exclusive. 3. alert("Above average performance");

The JavaScript prompt - Getting user input
Welcome ranu In this session we'll look at the JavaScript prompt. The prompt() is a method of the window object, just like alert() or confirm(). The format for prompt() is similar to alert() or confirm() except for one addition.
prompt("Message", "default value in the text field");

In addition to the "OK" and "Cancel" buttons, a prompt box also has a text field that is employed for gathering visitor input. JavaScript lets you specify a default text for this text field. This is optional, that is you can construct a prompt() without specifing the default text. In such cases, JavaScript displays an ugly "undefined" value in the text field. The information submitted by the visitor from prompt() can be stored in a variable, just as we had stored the value returned by confirm().
var name = prompt("What is your name", "Type you name here");

Once we have the value, we can write a customized greeting using document.write() as I have done or display an alert box.
var name = prompt("What is your name", "Type you name here"); alert("Hi " + name + "\nHope you are enjoying JavaScript!");

Click here to test the code. It's important to remember that the value returned by prompt() and subsequently stored in a variable will always be a string data type. This is fine if you are dealing with text, but might present problems to the code if you plan to receive numeric data through prompt(). Javascript provides two functions to convert this string value to a numeric data type; parseInt() and parseFloat(). The parseInt() converts a string to an integer value while parseFloat() parses the string converting it to a floating point number. Note: An integer is a whole number without any fractional part while floating-point numbers have a decimal part.

Now let's write a small script that takes a number from the visitor, checks whether its odd or even and displays the result through an alert box.
var n = prompt("Check your number", "Type your number here"); n = parseInt(n); if (n == 0) { alert("The number is zero"); } else if (n%2) { alert("The number is odd"); } else { alert("The number is even"); }

Click here to test the code When parseInt() or parseFloat() encounter alphabet or any non-digit character, parsing (conversion) stops and the functions return NaN, which means Not a Number. The only way to test for NaN is to use isNaN() function. We can make the code above more user-friendly by introducing one more if statement that checks for valid input.
var n = prompt("Check your n = parseInt(n); if (isNaN(n)) { alert("The input cannot } else { if (n == 0) { alert("The number is } else if (n%2) { alert("The number is } else { alert("The number is } } number", "Type your number here");

be parsed to a number");




Click here to test the code.

1. 2. 3. 4. 5.

With which object would you associate the prompt() method? Prompt() takes two arguments. Where are they displayed? The input from a prompt() is of which data type? What is the function of parseFloat() and parseInt()? What will be result if we send "abcd" through a prompt() input and pass it through parseInt()? 6. What is the use of isNaN()?

Possible Answers
1. Prompt(), like alert() and confirm() is a method of the window object. 2. The first argument is displayed on the prompt box while the second is displayed as value of the text field. The second argument is optional, which means that JavaScript will not throw an error if you skip it. However, in such cases, JavaScript displays "Undefined" in the text field. 3. String data type 4. parseFloat() converts an input to a floating-point number. parseInt() converts the input to an integer. 5. "abcd" is a string and cannot be parsed by parseInt(). JavaScript returns NaN (Not a Number). 6. isNaN() is employed to check if the number is valid or not.

Global and Local variables in JavaScript Functions
JavaScript functions help us divided our script into discrete chunks of code. Functions contain blocks of statements that can be regarded as separate entities from the main script because they are only executed when the function is called.

What are Local and Global variables?
When a function is defined certain variables used for storing values are incorporated inside the function. These variables are found and used only inside these functions. Since functions are separate from the main code, it's advisable to use variables that are initialized only when a function is called and die when the execution comes out of the function. Variables that exist only inside a function are called Local variables. They have no presence outside the function. The values of such Local variables cannot be changed by the main code or other functions. This results in easy code maintenance and is especially helpful if many programmers are working together on the same project.

Variables that exist throughout the script are called Global variables. Their values can be changed anytime in the code and even by other functions.

What is "variable scope"?
Local variables exist only inside a particular function hence they have Local Scope. Global variables on the other hand are present throughout the script and their values can be accessed by any function. Thus, they have Global Scope.

How to initialize a Local variable?
Any variable that is initialized inside a function using the var keyword will have a local scope. If a variable is initialized inside a function without var, it will have a global scope. A local variable can have the same name as a global variable.
var a = 10; disp_a(); function disp_a() { var a = 20; alert("Value of 'a' inside the function " + a); } alert("Value of 'a' outside the function " + a);

Check the code We first declare a global variable a and assign it a value of 10. Then we call a function in which we again initialize a variable named a. Since we have used the var keyword inside the function, this variable will have a local scope. Once we come out of the function, the local variable no longer exists and the global variable takes over. Now, let's see how we can change the value of a global variable in a function.
var a = 10; disp_a(); function disp_a() { a = 20; alert("Value of 'a' inside the function " + a); } alert("Value of 'a' outside the function " + a);

Check the code

In this case, we don't use the var keyword, hence the global variable is used inside the function.

The JavaScript "return" statement in a function
The statements in a function are executed line by line, from top to bottom. This flow of execution can be stopped by including a return statement, which causes the function to return a value, hence the statements after return are not executed. Its syntax is:
return expression as in: function cal_avg() { var avg = sum_total / n; return avg; }

In the above code, the value of variable avg is returned by the function.

1. How are local variables initialized? 2. What is the final value of variable sum?
3. var sum = 0; 4. function add_t() 5. { 6. var sum = sum + 20; 7. } 8. 9. add_t() 10. 11. sum = sum + 1;

Possible Answers
1. Local variables are initialized using the var keyword inside a function. 2. Variable sum = 1;

Understanding JavaScript for Loop
The main strength of any programming language is its ability to process blocks of code repeatedly. Computers are especially adept at perfoming repeated calculations. JavaScript, like other programming languages, provides us with loop. Statements placed inside loops are executed a set number of times... or even infinitely.

We'll look at the for loop in this session. The while and do...while will be explained in the next session. Here is the format of a for loop:
for (Initialization statements; Condition; Updation statements) { ... statements ... }

When the JavaScript interpreter comes across a for loop, it executes the initialization statements and then checks the condition. Only when the condition returns 'true', the interpreter enters the loop. After the first iteration, the updation statements are executed and then the condition is evaluated again. This continues till the condition returns 'false' and the loop stops. Some important points to note are:
  

The initialization statements are executed once; only when the for loop is encountered. After execution of initialization statements, the condition is evaluated. After every iteration, the updation statements are executed and then the condition is checked.

We can use a for loop to print digits 1 to 10 in an alert box.
var msg = ""; for (var x = 1; x <= 10; x++) { msg = msg + x + "\n"; } alert(msg);

Click here for results First, the variable x is initialized to 1, the condition is then evaluated. Since x is less than equal to 10, the statements inside the for loop are executed. The JavaScript interpreter then runs the updation statement that adds 1 to variable x. The condition is again checked. This goes on till the value of x becomes larger than 10. At this point, the statement immediately following the for loop is executed.

Displaying the 12 times table in an alert box
var msg = ""; var res = "0"; for (var x = 1; x <= 12; x++) {

res = 12 * x; msg = msg + "12 X " + x + " = " + res + "\n"; } alert(msg);

Click here for results

1. How many times is the condition evaluated in a for loop? 2. In a for loop, how many times are the initialization statements executed? 3. How many times will the following for loop be executed?
4. for (a = 0; a <= 10; a = a + 2) 5. { 6. ... statements ... 7. }

8. How many times will the following for loop be executed?
9. for 10. 11. 12. (b = 20; b <= 10; b++) { ... statements ... }

13. What will be displayed in the alert box at the nd of script execution?
14. var y = 0; 15. for (x = 0; x <= 5; x++, y = y + 50) 16. { 17. y = y + 10; 18. } 19. alert("The value of y is " + y);

20. Create a script that calculates the average of 5 numbers entered by the visitor through a prompt? 21. Change the script above and make it more flexible. Ask the visitor for the total number of numbers and then find the average.

Possible Answers
1. 2. 3. 4. 5. 6. The condition is evaluated at the beginning of the loop and at every iteration. The initialization statements are executed only once, at the beginning. Six times, when a = 0, 2, 4, 6, 8 and 10. None The final value of y is 360.

7. var msg = ""; 8. var num = 0; 9. var sum = 0; 10. var avg = 0; 11. for (var x = 1; x <= 5; x++) 12. { 13. num = prompt("This script calculates the average of 5 numbers", "Number " + x);

14. num = parseInt(num); 15. sum = sum + num; 16. } 17. avg = sum / 5; 18. alert("The average of the 5 numbers is " + avg);

After initializing all the required variables, we run a for loop five times to gather input from the visitor. The input is then converted to a number through parseInt() and added to the variable sum. At the end, the average is calculated and displayed in an alert box. 19.
20. var msg = ""; 21. var num = 0; 22. var sum = 0; 23. var avg = 0; 24. var t = prompt("For how many numbers would you like to find the average?", ""); 25. t = parseInt(t); 26. for (var x = 1; x <= t; x++) 27. { 28. num = prompt("This script calculates the average of 5 numbers", "Number " + x); 29. num = parseInt(num); 30. sum = sum + num; 31. } 32. avg = sum / t; 33. alert("The average is " + avg);

A modification of the above script. We introduce a prompt() at the very beginning through which we get the total number of numbers. This value is used in the for loop to generate the requisite number of prompts and is also used in the calculation of the average.

JavaScript While Loop
The JavaScript while loop is much simpler than the for loop. It consists of a condition and the statement block.
while (condition) { ...statements... }

As long as the condition evaluates to 'true', the program execution will continues to loop through the statements. In the previous session, we had used the for loop to display digits 1 to 10 in an alert box. We'll now employ the while loop to do the same thing.
var msg = "";

var x = 1; while (x <= 10) { msg = msg + x + "\n"; x++; } alert(msg);

Click here to check the code Note that the initialization statement (X = 1) has been placed before the loop. The condition lies between the parenthesis and the updation statement (x++) is present inside the statement block. It's a common error by beginners to forget the updation statement in which case the codition will never evaluate to 'false' and this will result in an infinite loop. To avoid such situations, my humble advice is to write the updation statement right after starting the statement block. You can then build the rest of the code in the statement block. We can also employ the while loop to display the 12 times table as we had done with for.
var msg = ""; var x = 1; var res = 0; while (x <= 10) { res = 12 * x; msg = msg + "12 X " + x + " = " + res + "\n"; x++; } alert(msg)

Click here to check the code If the condition in while evaluates to 'false' at the very beginning, the loop is skipped altogether and program execution starts at the statement immediately following the loop.

The do-while loop
You can consider the do-while loop as a modified version of the while loop. Here, the condition is placed at the end of the loop and hence, the loop is executed at least once.
var x = 20; do { alert("The number is " + x); x++; } while (x <= 10);

Click here to check the code In the code above, the value of variable x is 20, hence the condition evaluates to 'false'. However, the loop is executed once since the condition is presented at the end of the loop and not at the beginning.

1. If the value of variable num is 20, how many times will the following while loop be executed?
2. while (num <= 30) 3. { 4. ... statements ... 5. num = num + 3; 6. }

7. How many times is the while loop executed in the following code?
8. var b = 45; 9. var a = 14; 10. while (a < 50) 11. { 12. document.write("All is well with me"); 13. b = b + 5; 14. }

15. If the condition evaluates to 'false', how many times is the do-while loop executed and why?

Possible Answers
1. Four times 2. Infinite times since there is no update statement for variable a inside the while loop. 3. Once, because the condition is present at the end of the loop.

JavaScript break And continue Statements For Loops
JavaScript provides commands through which iterations of a loop can be skipped or stopped. These commands are most commonly used along with an if statement inside the loop.
 

continue: causes the iteration to be skipped break: causes the loop to stop and program execution to begin at the statement immediately following the loop.

For example, continue can be employed to display only the even numbers between 1 to 20, skipping the odd numbers.

var msg = ""; for (var x = 0; x <=20; x++) { if (x%2) { continue; } msg = msg + x + "\n"; } alert(msg);

Click here to check the results The condition in if checks for a remainder when variable x is divided by 2. Thus, for odd numbers, the condition will be 'true' and the loop will be skipped because of continue.

Similarly, break is employed to stop loop iterations completely.
var msg = ""; var t = 1; while (t <= 10) { if (t == 8) { break; } msg = msg + t + "\n"; t++; } alert(msg);

Click here to check the results Loop iteration stops when the value of variable t equals 8.

1. In the code below, which numbers are displayed in the alert box?
2. var msg = ""; 3. for (var x = 0; x < 10; x++) 4. { 5. if (x == 5 || x == 7) 6. { 7. continue; 8. } 9. msg = msg + x + "\n"; 10. } 11. alert(msg);

12. How can you display the odd numbers between 1 to 20 WITHOUT the use of continue?

Possible Answers
1. 0, 1, 2, 3, 4, 6, 8 and 9. 2.
3. var msg = ""; 4. for (var x = 1; x <= 20; x = x + 2) 5. { 6. msg = msg + x + "\n"; 7. } 8. alert(msg);

var msg = ""; var x = 1; while (x <= 20) { msg = msg + x + "\n"; x = x + 2; } alert(msg);

Changing Images on Mouseover Using JavaScript

The onmouseover event handler is used for generating various kinds of interactivity on web pages. It's most often used for image rollovers. Image change on mouse over is actually quite simple once we understand the logic.
    

To start off, we make two images, one for mouseover and the other for mouseout. The image that signifies mouseout is displayed in the <IMG> tag. The image is given a name using the NAME attribute of <IMG> tag. This tag is surrounded by <A> tags, which contain the onmouseover() and onmouseout() event handlers. When a mouse cursor is brought over an image, the event is captured by onmouseover(). This event handler changes the image to another by employing the src property of the Image object. When the mouse cursor is removed from the image, we utilize the pnmouseout() to capture the event. This event handler changes the image back to the original.

Here are the two images I made: icon1.gif: Image for Mouse Out icon2.gif: Image for Mouse Over

We'll now construct an image tag and give the image a name using its NAME attribute.
<IMG SRC="icon1.gif" NAME="but" WIDTH="100" HEIGHT="50" BORDER="0" ALT="...">

We use icon1.gif as the value for the SRC attribute since this is the image used for mouseout. The image is named but. The two event handlers are placed inside the starting <A> tag.
<A HREF="some.html" onmouseover="document.but.src='icon2.gif'" onmouseout="document.but.src='icon1.gif'"> <IMG SRC="icon1.gif" NAME="but" WIDTH="100" HEIGHT="50" BORDER="0" ALT="..."> </A>

As you would have guessed, images are a part the document object. The src property of the image object determines the source of the image. Thus, when the mouse cursor is brought over the image, the event is captured by onmouseover() that changes the src property, icon2.gif in our case. The opposite happens when the mouse is taken off the image. You should also note that the image is refered to by its name. If this was not so, JavaScript would be confused as to which image to change!

1. Why do you require the NAME attribute of the <IMG> tag to be used for image rollovers? 2. How can you change an image? (The most important statement) 3. If we use onclick() event handler instead of onmouseover() and onmouseout(), will the image change when we click on it?

Possible Answers
1. The NAME attribute is required so that JavaScript knows which image to work on. 2. An image can be changed by changing the value of it's src property through document.image_name.src.

3. Yes, the image will change.

JavaScript - Image Change Using Functions
The main use of function is to prevent us from writing the same code again and again because we can call the same function with a different set of parameters. In the image roll-over script of the previous session, the code for changing the image was placed inside the event handlers. This is fine if there are one or two images. In case of several images, it is advisable to pack the code in a function that can be called repeatedly by event handlers using different parameters. There are two important things in an image roll-over code. One is the image name and the other is the image source. Thus, we have to construct a function that accepts these two arguments and changes the image source.
function roll_over(img_name, img_src) { document[img_name].src = img_src; }

We can now call this function from our even handlers and pass it the two arguments.
<A HREF="some.html" onmouseover="roll_over('but1', 'icon2.gif')" onmouseout="roll_over('but1', 'icon1.gif')"> <IMG SRC="icon1.gif" WIDTH="100" HEIGHT="50" NAME="but1" BORDER="0"> </A>

1. You've seen how we can change an image on mouseover. How do you think, two images can be changed with a single mouse over?

Possible Answers
1. Two images can be modified on a single mouseover by constructing a function that changes the src property of two image objects. To learn more about this, click here.

Generating Random Numbers in JavaScript

To generate random numbers with JavaScript we employ the random() method of the Math object. It returns a floating-point number between 0.0 and 1.0. JavaScript Math object has several methods and we shall encounter three on this page - the first one being random().
var rand_no = Math.random(); alert(rand_no);

In the code above, the random() method returns the number which we store in the variable rand_no and display through alert(). Click to display a random number. You'll notice that each time you click the link a new random number is generated and displayed. Now that we have our randomly generated number with JavaScript, let us see how we can use it in some of our applications.

How to use JavaScript random number
Suppose you want a random number between 1 and 100. How do you get it from the long decimal number thrown up by the random() method? The first step is to multiply the long decimal random number generated by the random() method with 100.
var rand_no = Math.random(); rand_no = rand_no * 100; alert(rand_no);

Click to get see a set of 10 random numbers. The code above will give us a random number between 0 and 10. All numbers will be a little more than 0 and a little les than 100 - and they still have the long tail of numbers after the decimal. The next step involves another method of the JavaScript Math() object called ceil().

JavaScript ceil() method
The JavaScript ceil() rounds a decimal number to the next higher integer. Thus,
Math.ceil(2.456) Math.ceil(46.9) Math.ceil(0.0006) //gives 3 //gives 47 // gives 1

To remove numbers after the decimal and provide us with an integer between 1 and 100, we will pass the random number generated by random() to ceil().
var rand_no = Math.random(); rand_no = rand_no * 100; rand_no = Math.ceil(rand_no);


Click to generate a random number between 1 and 100. The above set of statements can also be shortened to:
var rand_no = Math.ceil(100*Math.random()) alert(rand_no);

JavaScript generates random numbers based on a formula. In a sense this is not random because if you know the formula, you know which number will come up next. However, this works fine for the web applications you will develop. Get a list of 20 randomly gerenated numbers between 1 and 100. What if you want random numbers between 0 and 10? The question is important. Because if we use the above code, it will simply not work. Since ceil() always returns the next higher integer, all random number that are between 0 and 1 will be converted to 1. We will learn about another JavaScript method to solve this problem.

Math.floor() method
The floor() rounds a number down to the lower integer. Thus:
Math.floor(2.456) Math.floor(46.9) Math.floor(0.0006) Math.floor(1.0006) Math.floor(0.932) //gives 2 //gives 46 // gives 0 // gives 1 // gives 0

But this throws up another problem. Number between 0.9 and 1.0 will all be rounded down (after multiplying with 10) to 9! The solution lies in multiplying the random number generated by random() with 11 - one number more than the range.
var rand_no = Math.floor(11*Math.random()) alert(rand_no);

List of 20 random number between 0 and 10.

Random number from a given range
To generate random numbers from a given range, follow the steps below:
  

Get number between 0.0 and 1.0 from random() method. Multiply it with the difference of upper value and one less than the lower value of the range. Use floor() to convert it into an integer

Add the lower value of the range

var rand_no = Math.floor((10-4)*Math.random()) + 5; alert(rand_no);

The code above generates a random number between 5 and 10. Just to prove that this works beautifully click to get a list of 20 random number between 5 and 10

1. How would you generate a random number between 0 to 50? a href="ans31.html" target="_blank">

JavaScript Arrays - creating and storing values
An array can be regarded as a set of variables. This does not mean that the variables in an array are related to each other; they are still separate entities in themselves. Arrays helps us group variables, which we plan to use for a particular purpose because accessing their values becomes a lot easier this way. Consider the following table: Number 1 2 3 4 5 6 7 City name New York London New Delhi Sydney Tokyo Moscow Lima

To store these city names, we can either employ different variables such as city1, city2, city3 ... or insert these values into an array. Let's see how we make an array.
var city = new Array();

Each array is initialized using the new keyword with the Array() construct (Isn't this similar to using Date()?). So here we initialize and array called city. Now we fill this array with our values (city names).
city[0] city[1] city[2] city[3] city[4] city[5] city[6] = = = = = = = "New York"; "London"; "New Delhi"; "Sydney"; "Tokyo"; "Moscow"; "Lima";

Each variable in an array begins with the array name followed by a numeric value contained in a pair of square brackets. This numeric value signifies the Index Number of that variable in the array. Note, that arrays are zero-indexed, that is, they start at index value 0. Also, we don't need the var keyword to initialize individual variables of an array. JavaScript allows us to write the array initialization and assignment statements as one. Thus,
var city = new Array("New York", "London", "New Delhi", "Sydney", "Tokyo", "Moscow", "Lima");

Array values are accessed through their index names. We can use a for loop for this purpose.
var msg = ""; for (x = 0; x < 7; x++) { msg = msg + city[x] + "\n";; } alert(msg);

Click here for the result. Now, don't you see the usefulness of arrays? If we had the values in variables of different names (even city1, city2...), our alert() statement would be very long. Values stored in arrays can be changed just like other variable values. Further, you can increase or decrease the number of items in an array... but that's for laters. The length of an array is found though its length property. The code below, finds the length of the array, adds 50 to each value and displays the result in an alert box.
var num = new Array(200, 400, 300, 250, 670, 430, 220, 870, 30); var l = num.length var msg = ""; for (x = 0; x < l; x++) { num[x] = num[x] + 50; msg = msg + num[x]+ "\n"; } alert(msg);

Click here for the result. After initializing the array num and asigning values to it, we find its length and store the value in variable l. The variable is then used in a for loop where each array value is incremented by 50. Lastly, you can mix the data types in an array which means that in a single array, some variables can contain string while the other might contain numeric data and JavaScript wouldn't complain!

1. 2. 3. 4. 5.

How are arrays initialized? How is storing values in arrays beneficial to our code? Can array values be changed? Can we mix data types in a single array? Write a small script in which an array is assigned numeric values 10, 20, 30 to 100 using a for loop.

Possible Answers
1. Arrays are initialized using the new operator and the Array() construct.
2. var names = new Array(); 3. var marks = new Array();

4. Array values can be accessed using loops. The for is frequently used for this purpose. 5. Yes, array values can be changed. 6. JavaScript is a loosely typed language and allows for various data types in a single array. 7.
8. var n = new Array(); 9. var t = 10; 10. for (var x = 0; x < 9; x++) 11. { 12. t = t * (x + 1); 13. n[x] = t; 14. } 15. alert(n);

Random Text Display Using JavaScript
Our aim is to randomly display a text string from a set. It involves the following steps 1. 2. 3. 4. 5. 6. Initializing an array Storing the text strings in that array Finding the length of this array Using the Math.random() to generate a random number Using the randomly generated number as index for retrieving a text string from the array. Displaying the text through an alert() box or document.write()

var text_st = new Array("String1", "String2", "String3", "String4", "String5", "String6", "String7", "String8", "String9", "String10"); var l = text_st.length; var rnd_no = Math.floor(l*Math.random()); alert(text_st[rnd_no]);

Click here for the result. Thus, we first create our array and add elemnts to it - 10 in this case. To find the number of array elements, we employ the ARRAY_NAME.length property and store the value in a variable. The JavaScript Math.round() gets us a random number between 0.0 and 1.0 which we then multiply with the array length value. Lastly, the Math.floor() method rounds down the random floating point (decimal) number to an integer. This integer serves as the index number of the array and we display our randomly generated text. Note: Array are zero-indexed, thus, we can use the value of variable l (length of the array) directly because we are using floor() to round down to an integer.

When to randomply display text on a web page?
I have used this code on several web sites to display a random testimonial from a set. So each time the web page loads a testimonial is selected and displayed at random. The code can also be used to display a random quote or a greeting. One good thing about this is that my JavaScript array that stores the testimonials or quotes resides in an external file. If I want to update the set of testimonials to be displayed, I simply need to edit a single file.

1. No assignments here.

Random Image Display Using JavaScript
The steps involved in randomly displaying an image from a set are very similar to those used for displaying random text strings. 1. 2. 3. 4. Initializing an array Storing the image file names in that array Finding the length of this array Using the Math.random() to generate a random number

5. Using the randomly generated number as index for retrieving an image file name from the array. 6. Displaying the image.
var img_name = new Array("purple.gif", "red.gif", "blue.gif", "yellow.gif", "green.gif", "pink.gif"); var l = img_name.length; var rnd_no = Math.floor(l*Math.random()); document.r_img.src = img_name[rnd_no]; <img src="purple.gif" width="100" height="50" name="r_img" alt="Random image" />

In th code above, we have JavaScript array containing 6 images. The array length found from length is, thus, 6 - img_name[0] would be "purple.gif", img_name[1] would be "red.gif" and so on. We then use the Math.round() to get a random number, multiply it with the array length and round it up using Math.floor().

Click to display another random image. Note: Array are zero-indexed, so the last element in the array will the length of the array minus 1. However, since we are employing floor() to get an integer, we can use the value from ARRAY_NAME.length directly. You can also use the id attribute of the image tag instead of name; as:
var img_name = new Array("purple.gif", "red.gif", "blue.gif", "yellow.gif", "green.gif", "pink.gif"); var l = img_name.length; var rnd_no = Math.floor(l*Math.random()); document.getElementById("randomimage").src = img_name[rnd_no]; <img src="purple.gif" width="100" height="50" id="randomimage" alt="Random image" />

Click to display another random image.

When can you display random images on a web page?
A potential use of the random image displaying code is when you want to show a single banner from a set - though I would prefer using server-side scripts like PHP or Perl for this. I have also employed the code to randomly rotate images at a designated place on the web page.