Chap-5 Javascript
Chap-5 Javascript
Chapter 5
JavaScript Programming
5.1 Introduction
JavaScript is used in millions of Web pages to improve the design, validate forms, detect
browsers, create cookies, and much more. JavaScript is the most popular scripting language on
the internet, and works in all major browsers, such as Internet Explorer, Firefox, and Opera.
Scripting languages are usually interpreted rather than compiled. That means that a software
routine called an interpreter translate a program’s statements into machine code, code
understandable by a particular type of computer, before executing them every time the program
is run. Compiled languages, on the other hand, are translated into machine code and stored for
later execution. When the compiled program is run, it executes immediately without further need
of inFaterpretation; it was interpreted into machine code when it was compiled. Because
programs written in interpreted languages must be translated into machine code every time they
are run, they are typically slower than compiled programs. However, this does not usually
present a problem for the small applications for which scripting languages are generally used.
Being interpreted does have its advantages. One is platform independence. Because an
interpreter performs the translation, we can write the program once and run it on a variety of
platforms. In the case of JavaScript, the interpreter is built into Web browsers. Browsers are
available for a variety of platforms and operating systems. Another advantage is that scripting
languages are often loosely typed and more forgiving than compiled languages.
5.2 Purposes of Java script :-
JavaScript gives HTML designers a programming tool - JavaScript is a scripting
language with a very simple syntax!
JavaScript can put dynamic text into an HTML page - A JavaScript statement like
this: [Link]("<h1>" + name + "</h1>") can write a variable text into an HTML
page
JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML
element
JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
JavaScript can be used to detect the visitor's browser - A JavaScript can be used to
detect the visitor's browser, and - depending on the browser - load another page
specifically designed for that browser
JavaScript can be used to create cookies - A JavaScript can be used to store and
retrieve information on the visitor's computer
5.3 Running the JavaScript
Any time including JavaScript in an HTML document, we must enclose those lines inside a
<SCRIPT>...</SCRIPT> tag pair. These tags alert the browser program to begin interpreting all
the text between these tags as a script. Because other scripting languages (such as Microsoft’s
VBScript) can take advantage of these script tags, we must specify the precise name of the
Page 1 of 53
Internet Programming Lecture Note
language in which the enclosed code is written. Therefore, when the browser receives this signal
that our script uses the JavaScript language, it employs its built-in JavaScript interpreter to
handle the code.
JavaScript is case-sensitive. Hence, we must enter any item in our script that uses a JavaScript
word with the correct uppercase and lowercase letters. HTML tags (including the <SCRIPT>
tag) can be in the case of our choice, but everything in JavaScript is case-sensitive. JavaScript
should be pt between the following :-
<SCRIPT LANGUAGE=”text/JavaScript”>
//your script here
</SCRIPT>
Or
<SCRIPT type=”text/JavaScript”>
//your script here
</SCRIPT>
As shown above, the attribute name called LANGUAGE & TYPE can be used interchangeably.
But, commonly we use type attribute.
Here are some tips to remember when writing JavaScript commands:
JavaScript code is case sensitive (e.g. age and Age are different variables)
White space between words and tabs are ignored
Line breaks are ignored except within a statement
JavaScript statements end with a semi colon (;) but not always
Javascript can come at different places. There is a flexibility given to include JavaScript code
anywhere in an HTML document. But there are following most preferred ways to include
JavaScript in an HTML file.
Wherever we use/ define a JavaScript block in our web page, simply use the following block
of HTML.
<script type='text/JavaScript'>
// Your script goes here.
</script>
We can place these script blocks anywhere on the page that we wish, there are some rules
and conventions however.
But, for external external File, Use the SRC attribute of the <SCRIPT> tag to call JavaScript
code from an external text file.
This is useful if we have a lot of code or we want to run it from several pages, because any
number of pages can call the same external JavaScript file. The text file itself contains no
HTML tags. It is called by the following tag:
<SCRIPT type = "JavaScript" SRC = " url of javascript file">
Page 2 of 53
Internet Programming Lecture Note
</SCRIPT>
If we want to run the same JavaScript on several pages, without having to write the same
script on every page, we can write a JavaScript in an external file. Save the external
JavaScript file with a .js file extension. The external script cannot contain the <script>
</script> tags. To use the external script, point to the .js file in the "src" attribute of the
<script> tag.
JavaScripts is put in a page where it will be executed immediately while the page loads into
the browser. Sometimes we want to execute a script when a page loads, or at a later event,
such as when a user clicks a button.
Page 3 of 53
Internet Programming Lecture Note
The alert method is produces a browser alert box. These are incredibly useful for debugging
and learning the language. However, they are not good way to communicate with the users.
An alert box is often used if we 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. The Syntax is
[Link]("sometext"); or simply write as alert(“some text”)
Example belows:-
<html>
<head>
<script language="javascript">
[Link]("This message is written by JavaScript");
function message()
{
alert("message to display");
}
</script>
</head>
<body onload="message()">
<br><br><br><br><br><br>
<h1>I THANK YOU FOR EVERY THING YOU MADE!!!</H1>
</body>
</html>
Prompt box:- is used to allow a user to enter something according to the promotion. It is
written as [Link]("please enter your name") or simply write as prompt(“some
text”)
Example:-
<script>
var y=[Link]("please enter your name")
[Link](y)
</script>
Confirm Box:- A confirm box is often used if we 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. It has the following Syntax [Link]("sometext"); or simply write
confirm(“some text”)
Example1:
<script type=”text/javascript”>
var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK!"; }
else
{ x="You pressed Cancel!"; }
[Link] (x);
</script>
Example 2:-
<script>
Page 4 of 53
Internet Programming Lecture Note
var x=[Link]("Are you sure you want to quit")
if (x)
[Link]("Thank you.")
else
[Link]("Good choice.")
</script>
The Page Printing:- JavaScript helps us to implement this functionality using print function
of window object. The JavaScript print function [Link]() will print the current web
page when executed. We can call this function directly using onclick event as follows:
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>
<form>
<input type="button" value="Print" onclick="[Link]()" />
</form>
</body>
5.5 Working with Variables and Data
Data in java script may be text information displayed on the screen by a JavaScript statement or
the on/off setting of a radio button in a form. Each single piece of information in programming is
also called a value. Outside of programming, the term value usually connotes a number of some
kind; in the programming world, however, the term is not as restrictive. A string of letters is a
value. A number is a value. The setting of a check box (whether it is checked or not) is a value.
In JavaScript, a value can be one of several types as shown bellow:-
Page 5 of 53
Internet Programming Lecture Note
Variable names should avoid all punctuation symbols except for the underscore
character. Also, the first character of a variable name cannot be a numeral.
To put together, a variable name can contain letters of the alphabet, both capital
and small, number and _(underscore). Still, the name should start with letters of
the alphabet, or _, not digits
Example: see the following correct variable declaration,
var firstName;
var weight;
var he89;
var TH_;
Example: Wrong variable names:
Var first name; //space not allowed
Var 89he; //can’t start with digit
Var TH.; //punctuation mark not allowed
ii. Assigning Values to Variables
After the declaration shown above, the variables are empty which means they have no
data values yet. After declaring a variable, it is possible to assign a value to it by using
equal sign (=) as follows:
var myAge;
myAge = 25;
However, we can also assign values to the variables as:
var age=5;
[Link] Values to Undeclared Variables
To assign values to variables that have not yet been declared, the variables will
automatically be declared. These statements:
age=5;
The above statements have the same effect as:
var age=5;
iv. Redeclaring JavaScript Variables
If we redeclare a JavaScript variable, it will not lose its original value.
var age=5;
var age;
After the execution of the statements above, the variable x will still have the value of 5.
The value of x is not reset (or cleared) when we redeclare it.
Page 6 of 53
Internet Programming Lecture Note
i. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between variables or values. +, -,
*, /, %, ++, --
ii. JavaScript Assignment Operators
Assignment operators are used to perform arithmetic operation and then assign the result to
variables. Includes:- =, +=, -=, *=, /= and %=
iii. Comparison Operators
Comparison operators help to compare two or more values — whether two values are equal, for
example. These kinds of comparisons return a value of the Boolean type — true or false.
Includes:- >, >=, <, <=, ==, and !=
iv. Logical Operators
Logical operators are used to determine the logic between variables or values:- &&, ||
V. The Bitwise Operators:
There are following bitwise operators supported by JavaScript language Assume variable A
holds 2 and variable B holds 3 then:
Operato
Description Example
r
Page 7 of 53
Internet Programming Lecture Note
two positions is equivalent to multiplying by 4,
etc.
Operator Precedence
Individual operators Operator type
[] member
() new call / create instance
! ~ - + ++ -- typeof negation/increment
void delete
* / % multiply/divide
+- addition/subtraction
<< >> >>> bitwise shift
< <= > >= in instanceof relational
== != === !== equality
& bitwise-and
^ bitwise-xor
| bitwise-or
&& logical-and
|| logical-or
?: Conditional
= += -= *= /= %= <<= assignment
Page 8 of 53
Internet Programming Lecture Note
>>= >>>= &= ^= |=
, comma
Table operator precedence Java Script
Page 9 of 53
Internet Programming Lecture Note
{ [Link]("<b>Good day</b>"); }
else
{ [Link]("<b>Hello World!</b>"); }
</script>
Example:-
<script type="text/javascript">
var book = "maths";
if( book == "history" ){
[Link]("<b>History Book</b>");
}else if( book == "maths" ){
[Link]("<b>Maths Book</b>");
}else if( book == "economics" ){
[Link]("<b>Economics Book</b>");
}else{
[Link]("<b>Unknown Book</b>");
}
</script>
ii. Switch Statement:- A switch statement allows a program to evaluate an expression and
attempt to match the expression's value to a case label. If a match is found, the program
executes the associated statement. A switch statement looks as follows:
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
...
default:
statementsdefault
[break;]
}
Example 1:-
<script type="text/javascript">
var d=new Date();
theDay=[Link]();
switch (theDay)
{ case 5: [Link]("Finally Friday");
break;
case 6: [Link]("Super Saturday");
break;
case 0: [Link]("Sleepy Sunday");
break;
default:
[Link]("I'm looking forward to this weekend!"); }
</script>
The program first looks for a case clause with a label matching the value of expression. If found,
it then transfers control to that clause, executing the associated statements. If no matching label
Page 10 of 53
Internet Programming Lecture Note
is found, the program looks for the optional default clause. If no default clause is found, the
program continues execution at the statement following the end of switch. By convention, the
default clause is the last clause.
If break is omitted, the program continues execution at the next statement in the switch statement
when there is a matched statement.
Example 2:
switch (fruittype) {
case "Apples":
[Link]("Apples are $0.32 a pound.<br>");
break;
case "Bananas":
[Link]("Bananas are $0.48 a pound.<br>");
break;
case "Mangoes":
case "Papayas":
[Link]("Mangoes and papayas are $2.79 a pound.<br>");
break;
default:
[Link]("Sorry, we are out of " + fruittype + ".<br>");
}
Example 3:-
<script type="text/javascript">
var grade='A',’B’;
[Link]("Entering switch block<br />");
switch (grade)
{
case 'A': [Link]("Good job<br />");
case 'B': [Link]("Pretty good<br />");
case 'C': [Link]("Passed<br />");
case 'D': [Link]("Not so good<br />");
case 'F': [Link]("Failed<br />");
default: [Link]("Unknown grade<br />")
}
[Link]("Exiting switch block");
</script>
B. Working with Loops
A loop is a set of commands that executes repeatedly until a specified condition is met, and
JavaScript supports loop like for, do while, and while loop statements. In addition, we can use
the break and continue statements within loop statements.
i. for Loop
A for loop repeats until a specified condition evaluates to false. A syntax of for statement is:-
for ([initialization]; [condition]; [increment]){ Statement(s)}
Example 1: a program that adds numbers from 0 to 10
var counter = 100;
var sum = 0;
Page 11 of 53
Internet Programming Lecture Note
for (var i = 0; i <= counter; i++) {
sum = sum + i;
}
[Link](“the sum is ” + sum);
Example 2:-
<html> <body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
[Link]("The number is " + i); [Link]("<br />");
}
</script>
</body>
</html>
ii. do...while Statement
The do...while statement repeats until a specified condition evaluates to false. A do...while
statement written as follows:
do{
statement
}while (condition);
statement executes once before the condition is checked. If condition is true, the statement
executes again. At the end of every execution, the condition is checked. When the condition is
false, execution stops and control passes to the statement following do...while.
Example: the do loop iterates at least once and reiterates until i is no longer less than 5.
i=1;
do
{
i += 1;
[Link](i);
} while (i < 5);
iii. while Statement
A while statement executes its statements as long as a specified condition evaluates to true. A
while statement looks as follows:
while (condition){
statement
}
The condition test occurs before statement in the loop are executed. If the condition returns true,
statement is executed and the condition is tested again. If the condition returns false, execution
stops and control is passed to the statement following while.
<html>
<body>
Page 12 of 53
Internet Programming Lecture Note
<script type="text/javascript">
var i=0;
while (i<=10)
{
[Link]("The number is " + i);
[Link]("<br />");
i=i+1;
}
</script>
<I>THANK YOU BEING UNDERSTAND ME</I>
</body>
</html>
Syntax:
Example: The following example that prints out the properties of a Web browser's Navigator
object:
<script type="text/javascript">
var aProperty;
[Link]("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{
[Link](aProperty);
[Link]("<br />");
}
[Link]("Exiting from the loop!");
</script>
Test the output?
These are used to come out of a loop without reaching at its bottom or to skip a part of the code
block and want to start next iteration of the look when needed by users or programmers.
To handle all such situations, JavaScript provides break, label and continue statements. These
statements are used to immediately come out of any loop or to start the next iteration of any loop.
Example1: the following example loops until the value of loop counter is 5:
for (i = 0; i < 100; i++) {
if (i== 5)
break;
}
Page 13 of 53
Internet Programming Lecture Note
The continue statement can be used to restart a while, do-while, for, or label statement. When we
use continue, it terminates the current iteration and continues execution of the loop with the next
iteration. In contrast to the break statement, continue does not terminate the execution of the loop
entirely. In a while loop, it jumps back to the condition check, and in a for loop, it jumps to the
increment-expression. But, break statement is used to terminate loop.
Example 2: a program that adds numbers between 0 and 100 with the exception of 60, 70, and
80
<script type=”text/javascript”>
var counter = 100;
var sum = 0;
for (var i = 0; i <= counter; i++)
{
if(i==60 || i==70 || i==80)
continue;
sum = sum + i;
}
[Link](“the sum is ” + sum);
</script>
Note: Line breaks are not allowed between the continue or break statement and its label name.
Also, there should not be any other statement in between a label name and associated loop.
Example 1:
<script type="text/javascript">
<!--
[Link]("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++)
{
[Link]("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++)
{
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
[Link]("Innerloop: " + j + " <br />");
}
}
[Link]("Exiting the loop!<br /> ");
//-->
</script>
Page 14 of 53
Internet Programming Lecture Note
Example 2:
<script type="text/javascript">
<!--
[Link]("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 3; i++)
{
[Link]("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++)
{
if (j == 3){
continue outerloop;
}
[Link]("Innerloop: " + j + "<br />");
}
}
[Link]("Exiting the loop!<br /> ");
//-->
</script>
Page 15 of 53
Internet Programming Lecture Note
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!
C. Using Arrays
An array is an ordered collection of data. In JavaScript, arrays are limited to a table holding one
column of data, with as many rows as needed to hold data.
A JavaScript-enabled browser creates a number of internal arrays for the objects in HTML
documents and browser properties. For example, if our document contains five links, the browser
maintains a table of those links. To access them by number (with 0 being the first link) in the
array syntax as in [Link][0], which represents the first link in the document.
To initialize an array for script, use the new keyword to construct the object for
assigning the array object to a variable of our choice like:
var myArray = new makeArray(n) where n is the number of entries anticipated for the
array. This initialization does not make any array entries or create any placeholders.
Example: an array that stores the names of planets
planet = new Array(9); //an array with 9 entries
planet[0] = “Mercury”
planet[1] = “Venus”
planet[2] = “Earth”
planet[3] = “Mars”
planet[4] = “Jupiter”
planet[5] = “Saturn”
planet[6] = “Uranus”
planet[7] = “Neptune”
planet[8] = “Pluto”
The index number starts at 0 and end at n-1 for array of n entries to access them. For
example, to access the fifth planet in the planets array, we use:
planet[4]; //Jupiter
To deleting array entries, we can always set the value of an array entry to null or an
empty string to wipe out any data that used to occupy that space. But with the delete
operator, we could not completely remove the element. Deleting an array element eliminates
the index from the list of accessible index values but does not reduce the array’s length.
[Link]; // result: 9
delete planet[2];
[Link]; //result: 9
planet[2]; //result: undefined
Page 16 of 53
Internet Programming Lecture Note
Array Object Methods
o [Link](array2):- The [Link]() method allows to join two array objects into a
new array object. The action of concatenating the arrays does not alter the contents or
behavior of the two original arrays.
For example:
var array1 = new Array(1,2,3)
var array2 = new Array(“a”,”b”,”c”)
var array3 = [Link](array2) // result: array with values 1,2,3,”a”,”b”,”c”
If an array element is a string or number value (not a string or number object), the values are
copied from the original arrays into the new one. All connection with the original arrays ceases
for those items.
o [Link]([compareFunction]):- This methods returns array of entries in the order as
determined by the compareFunction algorithm.
For simple alphabetical sorting of string values in arrays, the plain [Link]() method does the
trick. A comparison function is passed two values from the array. The comparison function lets
the sort() method know which of the two items comes before the other, based on the value the
function returns. Assuming that the function compares two values, a and b, the returned value
reveals information to the sort() method:
every() Returns true if every element in this array satisfies the provided
testing function.
filter() Creates a new array with all of the elements of this array for which
the provided filtering function returns true.
forEach() Calls a function for each element in the array.
indexOf(value) Returns the first (least) index of an element within the array equal to
the specified value, or -1 if none is found.
join(separator) Joins all elements of an array into a string using separator
Page 17 of 53
Internet Programming Lecture Note
lastIndexOf(value) Returns the last (greatest) index of an element within the array equal
to the specified value, or -1 if none is found.
pop() Removes the last element from an array and returns that element.
push(value) Adds one or more elements to the end of an array and returns the new
length of the array.
reverse() Reverses the order of the elements of an array − the first becomes the
last, and the last becomes the first.
shift() Removes the first element from an array and returns that element.
unshift(value) Adds one or more elements to the front of an array and returns the
new length of the array.
Table array object methods
[Link]();
[Link]("<br>Reversed: ");
for(var i=0;i<[Link]; i++)
[Link](" " + grade[i]);
[Link]("<br>Search 80: " + [Link]("80"));
[Link]("<br>Converted to string: " + [Link]());
[Link]("<br>Sliced: " + [Link](2));
[Link]("<br>Spliced: " + [Link](1));
}
</script>
</head>
<body onLoad="arrayFunction();">
</body>
</html>
Example2:- Filter example
<html>
<head>
Page 18 of 53
Internet Programming Lecture Note
<title>JavaScript Array filter Method</title>
</head>
<body>
<script type="text/javascript">
if (![Link])
{
[Link] = function(fun /*, thisp*/)
{
var len = [Link];
if (typeof fun != "function")
throw new TypeError();
return res;
};
}
function isBigEnough(element, index, array) {
return (element >= 10);
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
[Link]("Filtered Value : " + filtered );
</script>
</body>
</html>
</script>
</body>
</html>
Returned array is : banana,mango,orange,sugar
Example 4:- on push
<html>
<head>
<title>JavaScript Array push Method</title>
</head>
Page 19 of 53
Internet Programming Lecture Note
<body>
<script type="text/javascript">
var numbers = new Array(1, 4, 9);
length = [Link](20);
[Link]("<br />new numbers is : " + numbers );
</script>
</body>
</html>
Page 20 of 53
Internet Programming Lecture Note
alert("Hello World!")
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>
Function Parameters:- Functions receive parameter values from the calling statement.
Parameters (also known as arguments) provide a mechanism for “handing off” a value
from one statement to another by way of a function call. If no parameters occur in the
function definition, both the function definition and call to the function have only empty
sets of parentheses. When a function receives parameters, it assigns the incoming values
to the variable names specified in the function definition’s parentheses. Consider the
following script segment:
function sayHiToFirst(first, second, third) {
alert(“Say hello, “ + first)
}
sayHiToFirst(“Gracie”, “George”, “Harry”)
sayHiToFirst(“Larry”, “Moe”, “Curly”)
After the function is defined in the script, the next statement calls function, passing three strings
as parameters. The function definition automatically assigns the strings to variables first, second,
and third. Therefore, before the alert() statement inside the function ever runs, first evaluates to
“Gracie,” second evaluates to “George,” and third evaluates to “Harry.” In the alert() statement,
only the first value is used and the alert reads
Say hello, Gracie
When the user closes the first alert, the next call to the function occurs. This time through,
different values are passed to the function and assigned to first, second, and third. The alert
dialog box reads
Say hello, Larry
Unlike other variables that defined in script, function parameters do not use the var keyword to
initialize them. They are automatically initialized whenever the function is called. Example :-
function getCookie(c_name)
{
if ([Link]>0)
{
c_start=[Link](c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=[Link](";",c_start);
if (c_end==-1) c_end=[Link]; return
Page 21 of 53
Internet Programming Lecture Note
unescape([Link](c_start,c_end));
}
} return "";
}
The function above first checks if a cookie is stored at all in the [Link] object. If the
[Link] object holds some cookies, then check to see if our specific cookie is stored. If
our cookie is found, then return the value, if not - return an empty string. Last, we create the
function that displays a welcome message if the cookie is set, and if the cookie is not set it will
display a prompt box, asking for the name of the user:
function checkCookie()
{
username=getCookie('username');
if (username!=null && username!="")
{ alert('Welcome again '+username+'!'); }
else
{
username=prompt('Please enter your name:',"");
if (username!=null && username!="")
{
setCookie('username',username,365);
}} }
The above two codes can come together as follow:
<html>
<head>
<script type="text/javascript">
function getCookie(c_name)
{
if ([Link]>0)
{
c_start=[Link](c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=[Link](";",c_start);
if (c_end==-1) c_end=[Link];
return unescape([Link](c_start,c_end));
}
}
return "";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
[Link]([Link]()+expiredays);
[Link]=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+[Link]());
}
function checkCookie()
{ username=getCookie('username');
Page 22 of 53
Internet Programming Lecture Note
if (username!=null && username!="")
{ alert('Welcome again '+username+'!'); }
else {
username=prompt('Please enter your name:',"");
if (username!=null && username!="")
{ setCookie('username',username,365);
}}}
</script>
</head>
<body onLoad="checkCookie()">
</body> </html>
The example above runs the checkCookie() function when the page loads. As indicated above,
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. The example below returns the
product of two numbers (a and b):
<html>
<head>
<script type="text/javascript">
function product(op1, op2){
return op1*op2;
}
</script>
</head>
<body>
<script type="text/javascript">
[Link](product(4,3));
</script>
</body>
</html>
Example:- to exponensial
<html>
<head>
<title>Javascript Method toExponential()</title>
</head>
<body>
<script type="text/javascript">
var num=77.1234;
var val = [Link]();
[Link]("[Link]() is : " + val );
[Link]("<br />");
val = [Link](4);
[Link]("[Link](4) is : " + val );
[Link]("<br />");
val = [Link](2);
[Link]("[Link](2) is : " + val);
[Link]("<br />");
val = [Link]();
[Link]("[Link]()is : " + val );
[Link]("<br />");
Page 23 of 53
Internet Programming Lecture Note
val = [Link]();
[Link]("77 .toExponential() is : " + val);
</script>
</body>
</html>
Example:- concatenate
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one" );
var str2 = new String( "This is string two" );
var str3 = [Link]( str2 );
Example:- replace
<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script type="text/javascript">
var re = /(\w+)\s(\w+)/;
var str = "zara ali";
var newstr = [Link](re, "$2, $1");
[Link](newstr);
</script>
</body>
Page 24 of 53
Internet Programming Lecture Note
var str = "Apples are round, and Apples are Juicy.";
[Link]([Link]( ));
</script>
</body>
i. Math Object:-
The predefined Math object has properties and methods for mathematical constants and
functions. For example, the Math object’s PI property has the value of pi (3.141...), which we
would use in an application as [Link]. Similarly, standard mathematical functions are methods
of Math. These include trigonometric, logarithmic, exponential, and other functions. For
example, if we want to use the trigonometric function sine, we would write: [Link](1.56).
Note that all trigonometric methods of Math take arguments in radians.
Page 25 of 53
Internet Programming Lecture Note
Functions of the Math Object
abs (x): returns the absolute value of x; the result has the same magnitude as x but has
positive sign.
acos (x): returns the arc cosine of x. The result is expressed in radians and ranges from +0 to
+π.
asin (x): returns the arc sine of x. The result is expressed in radians and ranges from −π/2 to
+π/2.
atan (x): returns the arc tangent of x. The result is expressed in radians and ranges from −π/2
to +π/2. atan2 (y, x)
cos (x): returns the cosine of x. The argument is expressed in radians.
Example: [Link](0);
exp (x): returns the exponential function of x (e raised to the power of x, where e is the base
of the natural logarithms). Example: [Link](3);
floor (x): returns the greatest number that is not greater than x and is equal to a mathematical
integer. If x is already an integer, the result is x. The value of [Link](x) is the same as the
value of -[Link](-x).
ceil (x): returns the smallest (closest to −∞) number value that is not less than x and is equal
to a mathematical integer. If x is already an integer, the result is x. The value of [Link](x)
is the same as the value of -[Link](-x).
Example:
[Link](1.6); //result: 1
[Link](1.6); //result: 2
log (x): returns the natural logarithm of x.
Example:
[Link](20);
max ( [ value1 [ , value2 [ , ... ] ] ] ):- used to return the largest of the resulting values from
the given arguments.
min ( [ value1 [ , value2 [ , ... ] ] ] ):- uses to return the smallest of the resulting values i.e
arguments.
pow (x, y): returns result of raising x to the power y. Example: [Link](5,2); //output: 25
random ( ):- Returns a number value with positive sign, greater than or equal to 0 but less
than 1, chosen randomly or pseudo randomly with approximately uniform distribution over
that range. This function takes no arguments.
round (x):- Returns the number value that is closest to x and is equal to a mathematical
integer. If two integer number values are equally close to x, then the result is the number
value that is closer to +∞. If x is already an integer, the result is x.
Example:
[Link](3.5); // output: 4
[Link](–3.5); //output: –3.
Example:- this example uses to show how we use math objects.
<html><body><script type="text/javascript">
[Link]([Link](0.60) + "<br />");
[Link]([Link]());
[Link]([Link](5,7) + "<br />");
Page 26 of 53
Internet Programming Lecture Note
[Link]([Link](5,7) + "<br />");
[Link]([Link](7.25,7.30));
</script> </body> </html>
The value of [Link](x) is the same as the value of [Link](x+0.5), except when x
is −0 or is less than 0 but greater than or equal to -0.5; for these cases [Link](x)
returns −0, but [Link](x+0.5) returns +0.
sin (x): returns the sine of x. The argument is expressed in radians.
Example: [Link](90);
sqrt (x): returns the square root of x.
tan (x): returns the tangent of x. The argument is expressed in radians.
Page 27 of 53
Internet Programming Lecture Note
[Link](val) 0-59 sets Minute of the specified hour
[Link](val) 0-59 sets Second within the specified minute
Table Date object methods
Example: display current date and time
today = new Date();
var date = [Link]();
var month = [Link]();
var year = [Link]();
[Link](“Today’s date: ”+date+”/”+month+”/”+year);
output:
Date today: 4/11/2010
Example: to set date to some past time like birth date
myBirthday = new Date(“September 11, 2001”)
result = [Link]() // result = 2, a Tuesday
[Link](2002) // bump up to next year
result = [Link]() // result = 3, a Wednesday
Method Description
charAt(index) Returns the character at the specified index.
Page 28 of 53
Internet Programming Lecture Note
concat(string) Combines the text of two strings and returns a new string.
indexOf(string, [start]) Returns the index within the calling String object of the first
occurrence of the specified value, or -1 if not found.
lastIndexOf(string,[start]) Returns the index within the calling String object of the last
occurrence of the specified value, or -1 if not found.
localeCompare(string2) Returns a number indicating whether a reference string comes
before or after or is the same as the given string in sort order.
length() Returns the length of the string.
split(delimiter [,limit]) Splits a String object into an array of strings by separating the
string into substrings.
substr(start [, length]) Returns the characters in a string beginning at the specified
location through the specified number of characters.
substring(start, end) Returns the characters in a string between the two indexes into a
string.
toLocaleLowerCase() The characters within a string are converted to lower case while
respecting the current locale.
toLocaleUpperCase() The characters within a string are converted to upper case while
respecting the current locale.
toLowerCase() Returns the calling string value converted to lower case.
Page 29 of 53
Internet Programming Lecture Note
KONRAD ZUSE
iv. Document Object
Document object contains properties and methods that can be used to access the page elements
of the current document.
Properties:
title - Current document title. If no title is defined, title contains “Untitled.”
location - Full URL of the document.
lastModified - A Date object-compatible string containing the date the document was
last modified.
bgColor - Background color, expressed as a hexadecimal RGB value compatible with
HTML syntax (for example, #FFFFF" for white). Equivalent to the BGCOLOR attribute
of the <BODY> tag.
fgColor - Foreground (text) color, expressed as a hexadecimal RGB value compatible
with HTM syntax. Equivalent to the TEXT attribute of the <BODY> tag.
linkColor - Hyperlink color, expressed as a hexadecimal RGB value compatible with
HTML syntax. Equivalent to the vlinkColor Visited hyperlink color, expressed as a
hexadecimal RGB value compatible with HTML syntax. Equivalent to the VLINK
attribute of the <BODY> tag.
alinkColor - Activated (after button press, before button release) hyperlink color,
expressed as a hexadecimal RGB value compatible with HTML syntax. Equivalent to the
ALINK attribute of the <BODY> tag.
forms[ ] - Array of form objects in the document, in the order specified in the source.
Each form has its own form object.
[Link] - The number of form objects within the document.
links[ ] - Array objects corresponding to all HREF links in the document, in the order
specified in the source.
[Link] - The number of HREF links in the document.
anchors[ ] - Array of all "named" anchors (between the <A NAME=""> and </A> tags)
within the document, in the order specified in the source.
[Link] - The number of named anchors in the document.
images[] - Image objects that correspond to each image on the page.
applets[] - Java applet objects that correspond to each applet on the page.
embeds[] - Plugins object that represent each plug-in on the page.
Methods:
write("string")-Writes string to the current window. string may include HTML tags.
writeln("string") - Performs the same as write(), but adds a carriage return. This affects
only preformatted text (inside a <PRE> or <XMP> tag).
clear( ) - Clears the window.
close( ) - Closes the window.
[Link]() – goes back to last visited page
[Link]() – goes forward just like clicking forward button on toolbar
[Link](location) – goes to the specified history location
Page 30 of 53
Internet Programming Lecture Note
Managing Events
Events are occurrences generated by the browser, such as loading a document, or by the user,
such as moving the mouse. They are the user and browser activities to which we may respond
dynamically with a scripting language like JavaScript.
There are several more events that we can capture with JavaScript. Here is a short list of events
that Web developers like to capture:
Page 31 of 53
Internet Programming Lecture Note
> A web page or an image loading
> Mousing over a hot spot on the web page
> Selecting an input box in an HTML form
> Submitting an HTML form
> A keystroke
Events are :-
onabort - Loading of an image is interrupted
o onblur - An element loses focus
o onchange - The content of a field changes
o onclick - Mouse clicks an object
o ondblclick - Mouse double-clicks an object
o onerror - An error occurs when loading a document or an image
o onfocus - An element gets focus
o onkeydown - A keyboard key is pressed
o onkeypress - A keyboard key is pressed or held down
o onkeyup - A keyboard key is released
o onload - A page or an image is finished loading
o onmousedown - A mouse button is pressed
o onmousemove - The mouse is moved
o onmouseout - The mouse is moved off an element
o onmouseover - The mouse is moved over an element
o onmouseup - A mouse button is released
o onreset - The reset button is clicked
o onresize - A window or frame is resized
o onselect - Text is selected
o onsubmit - The submit button is clicked
o onunload - The user exits the page
Page 32 of 53
Internet Programming Lecture Note
<input type="text" id="fname" onblur="upperCase()"><br>
<form action="tryjs_submitpage.htm" onsubmit="return validate()">
Name (max 10 chararcters): <input type="text" id="fname" size="20"><br />
Age (from 1 to 100): <input type="text" id="age" size="20"><br />
E-mail: <input type="text" id="email" size="20"><br />
<br />
<input type="submit" value="Submit">
</form>
</body>
</html>
Example 2: a program that adds or subtracts two numbers when respective button is clicked
<html>
<head>
<script language="JavaScript">
function adder(num1, num2)
{
var sum = 0;
sum = num1 + num2;
[Link]("The sum is " + sum);
}
function subtractor(num1, num2)
{
var difference = 0;
difference = num1 - num2;
[Link]("The difference is " + difference);
}
</script>
</head>
<body>
<form name="event_example">
<input type="button" value="add" name="add" onClick="adder(10,30)">
<input type="button" value="subtract" name="subtract" onClick="subtractor(20,50)">
</form>
</body>
</html>
5.11 Form Processing and Validation
Forms are widely used on the Internet. The form input is often sent back to the server or mailed
to a certain e-mail account. With the help of JavaScript the form input can easily be checked
before sending it over the Internet. It is sent only if the input is valid.
Page 33 of 53
Internet Programming Lecture Note
In the name field, we will receive an error message when nothing is entered. Age is number and
we expect a positive number only. If user enters characters which are not number, or negative
value, it is not valid age. So the script should check this and determine its validity.
The email field is a little bit more sophisticated. It shouldn’t work if there is no @ symbol in the
email because valid email addresses contain that symbol. The criteria for accepting the input as a
valid e-mail address is the @. The person may enter wrong emails which could pass as valid but
this is the least check we could do.
Page 34 of 53
Internet Programming Lecture Note
alert("No message written");
else
alert("Message ok");
}
</script>
</head>
<body>
<h2> <u> Form validation </u> </h2>
<form name="first">
Enter your name: <input type="text" name="urname"> <br>
Enter your age: <input type="text" name="age"> <br>
Enter your e-mail address: <input type="text" name="email"> <br>
write message: <textarea name="urmessage" cols=40 rows=10></textarea><br><br>
<input type="button" name="validate" value="Check Input"
onClick="check([Link])">
</body>
</html>
E-mail Validation The function below checks if the content has the general syntax of an email.
This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not
be the first character of the email address, and the last dot must at least be one character after the
@ sign:
function validate_email(field,alerttxt)
{
with (field)
{ apos=[Link]("@");
dotpos=[Link](".");
if (apos<1||dotpos-apos<2)
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
The entire script, with the HTML form could look something like this:
<html>
<head>
<script type="text/javascript">
function validate_email(field,alerttxt)
{
with (field)
{
apos=[Link]("@");
dotpos=[Link](".");
if (apos<1||dotpos-apos<2)
Page 35 of 53
Internet Programming Lecture Note
{alert(alerttxt);return false;}
else
{ return true;
}}}
function validate_form(thisform)
{
with (thisform)
{
If
(validate_email(email,"Not a valid e-mail address!")==false)
{[Link]();return false;}
}}
</script>
</head>
<body>
<form action="[Link]"
onsubmit="return validate_form(this);"
method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body>
</html>
Example:- The following code used to develop form webpage for different operations
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript><!--
function plus(){
var n1;
var n2;
n1=[Link];
n2=[Link];
n1=parseFloat(n1);
n2=parseFloat(n2);
[Link]=n1+n2;
}
function times(){
var n1;
var n2;
n1=[Link];
n2=[Link];
n1=parseFloat(n1);
n2=parseFloat(n2);
[Link]=n1*n2;
}
//--></SCRIPT>
Page 36 of 53
Internet Programming Lecture Note
</HEAD>
<BODY BGCOLOR="#FFFFCC">
<P><FORM name=addmult>
<P>Enter a number in each field:
<INPUT TYPE=text NAME=num1 VALUE="" SIZE=5>
<INPUT TYPE=text NAME=num2 VALUE="" SIZE=5><BR>
<INPUT TYPE=button VALUE="+" onclick="plus()">
<INPUT TYPE=button VALUE="*" onclick="times()"><BR>
<INPUT TYPE=reset VALUE="Reset Form"><BR>
<TEXTAREA NAME=result ROWS=3 COLS=27
WRAP=virtual></TEXTAREA>
</FORM>
</BODY>
</HTML>
The latest versions of JavaScript added exception handling capabilities. JavaScript implements
the try...catch...finally construct as well as the throw operator to handle exceptions. We can
catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax
errors. Here is the try...catch...finally block syntax:
<script type="text/javascript">
<!--
try {
// Code to run
[break;]
} catch ( e ) {
// Code to run if an exception occurs
[break;]
}[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>
The try block must be followed by either exactly one catch block or one finally block (or one of
both). When an exception occurs in the try block, the exception is placed in e and the catch
block is executed. The optional finally block executes unconditionally after try/catch.
Examples:Here is one example where we are trying to call a non existing function this is
causing an exception raise
Page 37 of 53
Internet Programming Lecture Note
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
try {
alert("Value of variable a is : " + a );
} catch ( e ) {
alert("Error: " + [Link] );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
You can use finally block which will always execute unconditionally after try/catch. Here is an
example:
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
try {
alert("Value of variable a is : " + a );
}catch ( e ) {
alert("Error: " + [Link] );
}finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
Page 38 of 53
Internet Programming Lecture Note
The throw Statement:
You can use throw statement to raise to built-in exceptions or we customized exceptions. Later these exceptions can be captured and we
can take an appropriate action. Following is the example showing usage of throw statement.
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
var b = 0;
try{
if ( b == 0 ){
throw( "Divide by zero error." );
}else{
var c = a / b;
}
}catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
You can raise an exception in one function using a string, integer, Boolean or an object and then you can capture that exception either in
the same function as we did above, or in other function using try...catch block.
Example 2 :- The example below determines the value of a variable called x. If the value of x is
higher than 10 or lower than 0 we are going to throw an error. The error is then caught by the
catch argument and the proper error message is displayed:
<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","");
try
{ if(x>10)
throw "Err1";
else if(x<0)
throw "Err2"; }
catch(er)
if
(er=="Err1")
alert("Error! The value is too high");
if(er == "Err2") alert("Error! The value is too low"); }
Page 39 of 53
Internet Programming Lecture Note
</script>
</body>
</html>
The onerror event handler was the first feature to facilitate error handling for JavaScript. The
error event is fired on the window object whenever an exception occurs on the page. Example:
<html>
<head>
<script type="text/javascript">
<!--
[Link] = function () {
alert("An error occurred.");
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
The onerror event handler provides three pieces of information to identify the exact nature of
the error:
Error message . The same message that the browser would display for the given error
URL . The file in which the error occurred
Line number . The line number in the given URL that caused the error
<html>
<head>
<script type="text/javascript">
<!--
[Link] = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
//-->
</script>
</head>
Page 40 of 53
Internet Programming Lecture Note
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
You can use onerror method to show an error message in case there is any problem in loading
an image as follows:
<img src="[Link]"
onerror="alert('An error occurred loading the image.')" />
You can use onerror with many HTML tags to display appropriate messages in case of errors.
Java Validate:-
Form validation used to occur at the server, after the client had entered all necessary data and then pressed the Submit button. If some of
the data that had been entered by the client had been in the wrong form or was simply missing, the server would have to send all the data
back to the client and request that the form be resubmitted with correct information. This was really a lengthy process and over
burdening server.
JavaScript, provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally
performs two functions.
Basic Validation - First of all, the form must be checked to make sure data was entered into each form field that required it.
This would need just loop through each field in the form and check for data.
Data Format Validation - Secondly, the data that is entered must be checked for correct form and value. This would need to
put more logic to test correctness of data.
We will take an example to understand the process of validation. Here is the simple form to proceed:
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/[Link]" name="myForm"
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
Page 41 of 53
Internet Programming Lecture Note
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{
Page 42 of 53
Internet Programming Lecture Note
}
//-->
</script>
This example shows how to validate an entered email address which means email address must
contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email
address, and the last dot must at least be one character after the @ sign:
<script type="text/javascript">
<!--
function validateEmail()
{
It is possible to use JavaScript to create animated images. The trick is to let a JavaScript change
between different images on different events. In the following example we will add an image that
should act as a link button on a web page. We will then add an onMouseOver event and an
onMouseOut event that will run two JavaScript functions that will change between the images.
Page 43 of 53
Internet Programming Lecture Note
The HTML Code
The HTML code looks like this:
<a href="[Link] target="_blank">
<img border="0" src="b_pink.gif" name="b1"
onmouseOver="mouseOver()"
onmouseOut="mouseOut()" />
</a>
Note that we have given the image a name to make it possible for JavaScript to address it later.
The onMouseOver event tells the browser that once a mouse is rolled over the image, the
browser should execute a function that will replace the image with another image.
The onMouseOut event tells the browser that once a mouse is rolled away from the image,
another JavaScript function should be executed. This function will insert the original image
again.
The JavaScript Code
The changing between the images is done with the following JavaScript:
<script type="text/javascript">
function mouseOver()
{
[Link] ="b_blue.gif";
}
function mouseOut()
{
[Link] ="b_pink.gif";
}
</script>
The function mouseOver() causes the image to shift to "b_blue.gif". The function mouseOut()
causes the image to shift to "b_pink.gif".
Example:-
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript><!--
function verify(){
with([Link]){
if(([Link]=="")||([Link]=="")||([Link]=="")){
alert("You have left one or more fields blank. Please supply the necessary
information, and re-submit the form.");
}
else {
[Link]="The following information has been added to our
guestbook:\r"+[Link]+"\r"+ [Link] +"\r" +[Link];
}
}
}
//--></SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFCC">
<P><FORM name=”infoform”>
Page 44 of 53
Internet Programming Lecture Note
<P><TABLE BORDER=0>
<TR>
<TD WIDTH=83>
<P>Name:
</TD>
<TD>
<P><INPUT TYPE=text NAME=fullname VALUE="" SIZE=32>
</TD>
</TR>
<TR>
<TD WIDTH=83>
<P>Address:
</TD>
<TD>
<P><INPUT TYPE=text NAME=address VALUE="" SIZE=32>
</TD>
</TR>
<TR>
<TD WIDTH=83>
<P>E-mail:
</TD>
<TD>
<P><INPUT TYPE=text NAME=email VALUE="" SIZE=32>
</TD>
</TR>
<TR>
<TD WIDTH=83>
<P><INPUT TYPE=button VALUE="Submit" onclick="verify()">
</TD>
<TD>
<P><INPUT TYPE=reset VALUE="Clear Your Information">
</TD>
</TR>
<TR>
<TD COLSPAN=2>
<P><TEXTAREA NAME=display ROWS=5 COLS=41
WRAP=virtual></TEXTAREA>
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>
We can use JavaScript to create a complex animation which includes but not limited to:
Page 45 of 53
Internet Programming Lecture Note
Fireworks
Fade Effect
Roll-in or Roll-out
Page-in or Page-out
Object movements
We might be interested in existing JavaScript based animation library. JavaScript can be used to move a
number of DOM elements (<img />, <div> or any other HTML element) around the page according to some sort of pattern determined
by a logical equation or function. JavaScript provides following two functions to be frequently used in animation programs.
setTimeout( function, duration) - This function calls function after duration milliseconds from now.
setInterval(function, duration) - This function calls function after every duration milliseconds.
clearTimeout(setTimeout_variable) - This function calls clears any timer set by the setTimeout() functions.
JavaScript can also set a number of attributes of a DOM object including its position on the
screen. You can set top and left attribute of an object to position it anywhere on the screen. Here
is the simple syntax:
Manual Animation:
So let's implement one simple animation using DOM object properties and JavaScript functions
as follows:
<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null;
function init(){
imgObj = [Link]('myImage');
[Link]= 'relative';
[Link] = '0px';
}
function moveRight(){
[Link] = parseInt([Link]) + 10 + 'px';
}
[Link] =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/[Link]" />
<p>Click button below to move the image to right</p>
Page 46 of 53
Internet Programming Lecture Note
<input type="button" value="Click Me" onclick="moveRight();" />
</form>
</body>
</html>
We are using JavaScript function getElementById() to get a DOM object and then
assigning it to a global variable imgObj.
We have defined an initialization function init() to initialize imgObj where we have set its
position and left attributes.
Finally, we are calling moveRight() function to increase left distance by 10 pixels. You
could also set it to a negative value to move it to the left side
Automated Animation:
In the above example we have seen , how an image moves to right with every click. We can automate this process by using JavaScript
function setTimeout() as follows:
<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = [Link]('myImage');
[Link]= 'relative';
[Link] = '0px';
}
function moveRight(){
[Link] = parseInt([Link]) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop(){
clearTimeout(animate);
[Link] = '0px';
}
[Link] =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/[Link]" />
<p>Click the buttons below to handle animation</p>
<input type="button" value="Start" onclick="moveRight();" />
<input type="button" value="Stop" onclick="stop();" />
</form>
Page 47 of 53
Internet Programming Lecture Note
</body>
</html>
Here we have add more spice. So let's see what is new here:
The moveRight() function is calling setTimeout() function to set the position of imgObj.
We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position.
<html>
<head>
<title>Rollover with a Mouse Events</title>
<script type="text/javascript">
<!--
if([Link]){
var image1 = new Image(); // Preload an image
[Link] = "/images/[Link]";
var image2 = new Image(); // Preload second image
[Link] = "/images/[Link]";
}
//-->
</script>
</head>
<body>
<p>Move your mouse over the image to see the result</p>
<a href="#" onMouseOver="[Link]=[Link];"
onMouseOut="[Link]=[Link];">
<img name="myImage" src="/images/[Link]" />
</a>
</body>
</html>
At the time of loading this page, the if statement checks for the existence of the image object. If the image object is
unavailable, this block will not be executed.
The Image() constructor creates and preloads a new image object called image1.
The src property is assigned the name of the external image file called /images/[Link].
Similar way we have created image2 object and assigned /images/[Link] in this object.
The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image.
The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is
triggered when the user's mouse moves away from the link (image).
When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is
moved away from the image, the original image is displayed.
When the mouse is moved away from the link, the initial image [Link] will reappear on the screen.
Page 48 of 53
Internet Programming Lecture Note
What are Cookies ?
Web Browser and Server use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website it is
required to maintain session information among different pages. For example one user registration ends after completing many pages.
But how to maintain user's session information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and
other information required for better visitor experience or site statistics.
How It Works ?
Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as
a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same
cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.
Expires : The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Domain : The domain name of your site.
Path : The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any
directory or page.
Secure : If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is
blank, no such restriction exists.
Name=Value : Cookies are set and retrieved in the form of key and value pairs.
Cookies were originally designed for CGI programming and cookies' data is automatically transmitted between the web browser and web
server, so CGI scripts on the server can read and write cookie values that are stored on the client.
JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete
the cookie or cookies that apply to the current web page.
Storing Cookies:
The simplest way to create a cookie is to assign a string value to the [Link] object, which looks like this:
Syntax:
[Link] = "key1=value1;key2=value2;expires=date";
Here expires attribute is option. If you provide this attribute with a valid date or time then cookie will expire at the given date or time and
after that cookies' value will not be accessible.
Note: Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape()
function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape()
function when you read the cookie value.
Example:
<html>
Page 49 of 53
Internet Programming Lecture Note
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
if( [Link] == "" ){
alert("Enter some value!");
return;
}
This will produce following result. Now enter something in the text box and press the button "Set
Cookie" to set the cookies.
Enter name:
Now your machine has a cookie called name. You can set multiple cookies using multiple key=value pairs separated by comma.
Reading Cookies:
Reading a cookie is just as simple as writing one, because the value of the [Link] object is the cookie. So you can use this
string whenever you want to access the cookie.
The [Link] string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value
is its string value.
You can use strings' split() function to break the string into key and values as follows:
Example:
<html>
<head>
<script type="text/javascript">
<!--
Page 50 of 53
Internet Programming Lecture Note
function ReadCookie()
{
var allcookies = [Link];
alert("All Cookies : " + allcookies );
Note: Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that
time please try to digest it.
This will produce following result. Now press the button "Get Cookie" to see the cookies which
you have set in previous section.
Note: There may be some other cookies already set on your machine. So above code will show you all the cookies set at your machine.
Example:
The following example illustrates how to set cookie expiration date after 1 Month :
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
[Link]( [Link]() + 1 );
cookievalue = escape([Link]) + ";"
[Link]="name=" + cookievalue;
[Link] = "expires=" + [Link]() + ";"
Page 51 of 53
Internet Programming Lecture Note
alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
Deleting a Cookie:
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set
the expiration date to a time in the past.
Example:
The following example illustrates how to delete cookie by setting expiration date one Month in
past :
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
[Link]( [Link]() - 1 );
cookievalue = escape([Link]) + ";"
[Link]="name=" + cookievalue;
[Link] = "expires=" + [Link]() + ";"
alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
Note that:-
Page 52 of 53
Internet Programming Lecture Note
language: This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although
recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
type: This attribute is what is now recommended to indicate the scripting language in use and its value should be set to
"text/javascript".
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
Page 53 of 53