Javascript
Javascript
CO NT EN T S
1. INTRODUCTION 107
2. STATEMENTS 109
4. FUNCTIONS 114
6. LOOPS 116
7. OBJECTS 118
An ISO 9001 : 2000 Recognised Institution
INTRODUCTION TO JAVASCRIPT
With the advent of Internet and Worldwide web, interactive communication at an exigency
has become a necessity for mankind. The worldwide web is a cluster of pages of information,
combining text, pictures and sound. Each page has a hyperlink that refers to another page on
the Net. The linked page can have further links to other such pages. This system of interlined
documents is called as hypertext. Browsers help in manipulating pages of hypertext information
to enhance interactivity between pages. One such Browser is the Netscape Navigator, developed
by Netscape communications, which incorporates Java, a programming language from Sun
Microsystems and JavaScript, a scripting language used to enhance the functionality of the
browser.
Javascript facilitates the developer with properties related to document windows, frames,
forms, loaded documents and links. This scripting language also traps user events so programs
can be developed for such events. This is an interpreter based language and source code files
are directly executed at runtime. Javascript includes built-in objects related to the current
windows and documents as well as objects such as Math, String and Date that contain
mathematical functions, string functions and Date functions respectively. Since Javascript is an
Object based language, it supports instances, methods and properties.
JavaScript is a scripting language most often used for client-side web development. JavaScript
is used in millions of Web pages to add functionality, validate forms, detect browsers, and much
more. JavaScript is the most popular scripting language on the internet, and works in all major
browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, and Opera.
· JavaScript was designed to add interactivity to HTML pages
· JavaScript is a scripting language
· A scripting language is a lightweight programming language
· A JavaScript consists of lines of executable computer code
· A JavaScript is usually embedded directly into HTML pages
· JavaScript is an interpreted language
· Everyone can use JavaScript without purchasing a license
NOTE Javascript scripts can be included anywhere in the header or body of an HTML file.
JAVASCRIPT 107
An ISO 9001 : 2000 Recognised Institution
Example
1) Open a blank document by choosing File->New->Blank option in the Netscape Navigator.
2) Set the Editor Preferences to Wordpad.exe or Notepad.exe.
3) Invoke the editor, save the file and type in the following script.
<html>
<head>
<title> Example2 </title>
<Meta name = “GENERATOR” content = “Mozilla/2.01gold (win 32)”>
</head>
<body> <script language = “Javascript”>
<!—Hide from other browsers
Document.write(“<h1><i>Welcome to the world of Internet!!!!</i></h1>”);
// stop hiding from other browsers à
</script>
</body>
</html>
Where to Put the JavaScript ?
JavaScripts in a page will be executed immediately while the page loads into the browser.
Sometimes we want to execute a script when a page loads, other times when a user triggers an event.
Scripts in the head section: Scripts to be executed when they are called, or when an
event is triggered, go in the head section.
<html>
<head>
<script type=”text/javascript”>
....
</script>
</head>
Scripts in the body section: Scripts to be executed when the page loads go in the body
section. When you place a script in the body section it generates the content of the page.
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
....
</script>
</body>
Scripts in both the body and the head section: You can place an unlimited number of
scripts in your document, so you can have scripts in both the body and the head section.
<html> <head>
<script type=”text/javascript”>
....
</script>
</head> <body>
<script type=”text/javascript”>
....
</script>
</body>
JAVASCRIPT 108
An ISO 9001 : 2000 Recognised Institution
STATEMENTS
JavaScript is a sequence of statements to be executed by the browser. Unlike HTML,
JavaScript is case sensitive - therefore watch the capitalization closely while writing JavaScript
statements, create or call variables, objects and functions.
JavaScript Statements
A JavaScript statement is a command to the browser. The purpose of the command is to
tell the browser what to do. This JavaScript statement tells the browser to write “Hello Dolly” to
the web page:
document.write(“Hello Dolly”);
It is normal to add a semicolon at the end of each executable statement. Most people think
this is a good programming practice, and most often you will see this in JavaScript examples on
the web. The semicolon is optional (according to the JavaScript standard), and the browser is
supposed to interpret the end of the line as the end of the statement. Because of this you will
often see examples without the semicolon at the end.
NOTE Using semicolons makes it possible to write multiple statements on one line.
JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each statement
is executed by the browser in the sequence they are written. This example will write a header
and two paragraphs to a web page:
<script type=”text/javascript”>
document.write(“<h1>This is a header</h1>”);
document.write(“<p>This is a paragraph</p>”);
document.write(“<p>This is another paragraph</p>”);
</script>
JavaScript Blocks
JavaScript statements can be grouped together in blocks. Blocks start with a left curly
bracket {, and ends with a right curly bracket }. The purpose of a block is to make the sequence of
statements execute together. This example will write a header and two paragraphs to a web page:
<script type=”text/javascript”> {
document.write(“<h1>This is a header</h1>”);
document.write(“<p>This is a paragraph</p>”);
document.write(“<p>This is another paragraph</p>”);
} </script>
JavaScript Comments
Comments can be added to explain the JavaScript, or to make it more readable. Single line
comments start with //. This example uses single line comments to explain the code:
<script type=”text/javascript”>
// This will write a header:
document.write(“<h1>This is a header</h1>”);
// This will write two paragraphs:
document.write(“<p>This is a paragraph</p>”);
document.write(“<p>This is another paragraph</p>”);
</script>
JAVASCRIPT 109
An ISO 9001 : 2000 Recognised Institution
JAVASCRIPT VARIABLES
Variables are “containers” for storing information. A variable can have a short name, like x,
or a more descriptive name like carname. Rules for JavaScript variable names:
· Variable names are case sensitive (y and Y are two different variables)
· Variable names must begin with a letter or the underscore character
Declaring (Creating) JavaScript Variables
Creating variables in JavaScript is most often referred to as “declaring” variables. You can
declare JavaScript variables with the var statement:
var x;
var carname;
After the declaration shown above, the variables have no values, but you can assign
values to the variables while you declare them:
var x=5;
var carname=”Volvo”;
JAVASCRIPT OPERATORS
Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values. Given
that y=5, the table below explains the arithmetic operators: S
JAVASCRIPT 110
An ISO 9001 : 2000 Recognised Institution
Assignment Operators
Assignment operators are used to assign values to JavaScript variables. Given that x=10
and y=5, the table below explains the assignment operators:
Operator Example Same As Result
= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0
Logical Operators
Logical operators are used to determine the logic between variables or values. Given that
x=6 and y=3, the table below explains the logical operators:
Operator Description Example
&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on
some condition.
Syntax : variablename=(condition)?value1:value2
Example greeting=(visitor==”PRES”)?”Dear President “:”Dear “;
If the variable visitor has the value of “PRES”, then the variable greeting will be assigned
the value “Dear President “ else it will be assigned “Dear”.
JAVASCRIPT 111
An ISO 9001 : 2000 Recognised Institution
CONDITIONAL STATEMENTS
In JavaScript we have the following conditional statements:
if use this statement to execute some code only if a specified condition is true
if...else use this statement to execute some code if the condition is true and another
code if the condition is false
if...else if....else use this statement to select one of many blocks of code to be executed
switch use this statement to select one of many blocks of code to be executed
IF STATEMENT
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
Example 1
<script type=”text/javascript”>
//Write a “Good morning” greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();
if (time<10)
{ document.write(“<b>Good morning</b>”); }
</script>
IF...ELSE STATEMENT
To execute some code if a condition is true and another code if the condition is not true,
use the if....else statement.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example
<script type=”text/javascript”>
//If the time is less than 10, you will get a “Good morning” greeting.
//Otherwise you will get a “Good day” greeting.
var d = new Date();
var time = d.getHours();
if (time < 10)
{ document.write(“Good morning!”); }
else
{ document.write(“Good day!”); }
</script>
JAVASCRIPT 112
An ISO 9001 : 2000 Recognised Institution
SWITCH STATEMENT
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in
the structure. If there is a match, the block of code associated with that case is executed. Use
break to prevent the code from running into the next case automatically.
Example
<script type=”text/javascript”>
//You will receive a different greeting based on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{ case 5: document.write(“Finally Friday”); break;
case 6: document.write(“Super Saturday”); break;
default: document.write(“I’m looking forward to this weekend!”);
}
</script>
JAVASCRIPT 113
An ISO 9001 : 2000 Recognised Institution
FUNCTIONS
A function contains code that will be executed by an event or by a call to that function.
Call a function from anywhere within the page.
Functions can be defined both in the <head> and in the <body> section of a document.
However, to assure that the function is read/loaded by the browser before it is called, it could be
wise to put it in the <head> section.
Example
<html>
<head>
<script type=”text/javascript”>
function displaymessage()
{
alert(“Hello World!”);
}
</script>
</head>
<body>
<form>
<input type=”button” value=”Click me!”
onclick=”displaymessage()” >
</form>
</body>
</html>
If the line: alert(“Hello world!!”) in the example above had not been put within a function, it
would have been executed as soon as the line was loaded. Now, the script is not executed
before the user hits the button. We have added an onClick event to the button that will execute
the function displaymessage() when the button is clicked.
How to Define a Function
The syntax for creating a function is:
function functionname(var1,var2,...,varX)
{
some code
}
var1, var2, etc are variables or values passed into the function. The { and the } defines
the start and end of the function.
NOTE (a) A function with no parameters must include the parentheses () after the
function name.
function functionname()
{
some code
}
JAVASCRIPT 114
An ISO 9001 : 2000 Recognised Institution
(b) The word “function” must be written in lowercase letters, otherwise a JavaScript
error occurs! Also note that you must call a function with the exact same capitals
as in the function name
The return Statement
The return statement is used to specify the value that is returned from the function. So,
functions that are going to return a value must use the return statement.
Example
The function below should return the product of two numbers (a and b):
function prod(a,b)
{
x=a*b;
return x;
}
When you call the function above, you must pass along two parameters:
product=prod(2,3);
The returned value from the prod() function is 6, and it will be stored in the variable called
product.
POPUP BOXES
Alert Box
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click “OK” to proceed.
Syntax:
alert(“sometext”);
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either “OK” or “Cancel” to proceed.
If the user clicks “OK”, the box returns true. If the user clicks “Cancel”, the box returns false.
Syntax:
confirm(“sometext”);
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed
after entering an input value. If the user clicks “OK” the box returns the input value. If the user
clicks “Cancel” the box returns null.
Syntax:
prompt(“sometext”,”defaultvalue”);
JAVASCRIPT 115
An ISO 9001 : 2000 Recognised Institution
LOOPS
Very often when you write code, you want the same block of code to run over and over
again in a row. Instead of adding several almost equal lines in a script we can use loops to
perform a task like this. In JavaScript there are two different kind of loops:
· for - loops through a block of code a specified number of times
· while - loops through a block of code while a specified condition is true
FOR LOOP
The for loop is used when you know in advance how many times the script should run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
Example
Explanation: The example below defines a loop that starts with i=0. The loop will continue
to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
NOTE The increment parameter could also be negative, and the <= could be any
comparing statement.
<html>
<body>
<script type=”text/javascript”>
var i=0;
for (i=0;i<=10;i++)
{
document.write(“The number is “ + i);
document.write(“<br />”);
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
.................
WHILE LOOP
The while loop is used when you want the loop to execute and continue executing while the
specified condition is true.
while (var<=endvalue)
{
code to be executed
}
JAVASCRIPT 116
An ISO 9001 : 2000 Recognised Institution
Example
The example below defines a loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
<html>
<body>
<script type=”text/javascript”>
var i=0;
while (i<=10)
{
document.write(“The number is “ + i);
document.write(“<br />”);
i=i+1;
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
...........
DO...WHILE LOOP
The do...while loop is a variant of the while loop. This loop will always execute a block of
code ONCE, and then it will repeat the loop as long as the specified condition is true. This loop
will always be executed at least once, even if the condition is false, because the code is
executed before the condition is tested.
do
{
code to be executed
}
while (var<=endvalue);
Example
<html>
<body>
<script type=”text/javascript”>
var i=0;
do
{
document.write(“The number is “ + i);
document.write(“<br />”);
i=i+1;
}
while (i<0);
</script>
</body>
</html>
Result
The number is 0
JAVASCRIPT 117
An ISO 9001 : 2000 Recognised Institution
OBJECTS
String Object The String object is used to manipulate a stored piece of text.
Example: The following example uses the toUpperCase() method of the String object to convert a
string to uppercase letters:
var txt=”Hello world!”;
document.write(txt.toUpperCase());
The code above will result in the following output:
HELLO WORLD!
Date Object The Date object is used to work with dates and times. We define a Date object
with the new keyword. The following code line defines a Date object called myDate:
var myDate=new Date()
NOTE The Date object will automatically hold the current date and time as its initial value!
Manipulate Dates We can easily manipulate the date by using the methods available for the
Date object. In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 5 days into the future:
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
Comparing Dates The Date object is also used to compare two dates. The following example
compares today’s date with the 14th January 2010:
var myDate=new Date();
myDate.setFullYear(2010,0,14);
var today = new Date();
if (myDate>today)
{ alert(“Today is before 14th January 2010”); }
else
{ alert(“Today is after 14th January 2010”); }
JAVASCRIPT 118
An ISO 9001 : 2000 Recognised Institution
</html>
It’s been: 38.69718433298453 years since 1970/01/01!
getDay() Use getDay() and an array to write a weekday, and not just a number.
<html>
<body>
<script type=”text/javascript”>
var d=new Date();
var weekday=new Array(7);
weekday[0]=”Sunday”;
weekday[1]=”Monday”;
weekday[2]=”Tuesday”;
weekday[3]=”Wednesday”;
weekday[4]=”Thursday”;
weekday[5]=”Friday”;
weekday[6]=”Saturday”;
document.write(“Today it is “ + weekday[d.getDay()]);
</script>
</body>
</html>
Today it is Tuesday
Math Object
The Math object allows to perform common mathematical tasks. The Math object includes
several mathematical values and functions.
Mathematical Values JavaScript provides eight mathematical values (constants) that can be
accessed from the Math object. These are: E, PI, square root of 2, square root of 1/2, natural log
of 2, natural log of 10, base-2 log of E, and base-10 log of E. You may reference these values
from your JavaScript like this:
Math.E Math.PI Math.SQRT2
Math.SQRT1_2 Math.LN2 Math.LN10
Math.LOG2E Math.LOG10E
Mathematical Methods In addition to the mathematical values that can be accessed from
the Math object there are also several functions (methods) available.
(a) The following example uses the round() method of the Math object to round a number to the
nearest integer:
document.write(Math.round(4.7));
The code above will result in the following output: 5
(b) The following example uses the floor() and random() methods of the Math object to return a
random number between 0 and 10:
document.write(Math.floor(Math.random()*11));
The code above can result in the following output:
4
JAVASCRIPT 119