Internet Technologies
Internet Technologies
A scripting language is used to write scripts. These contain a series of commands that are
interpreted one by one at runtime unlike programming languages that are compiled first
before running.
Nowadays, scripts are generally associated with web development where they are widely
used to make dynamic web applications. Scripting languages can be divided into two
categories:
x
Server-side scripting languages create the scripts that run on the server and hence
minimize the workload of a browser. The functionality of your website is written in
those scripting languages. The most commonly used server-side scripting languages
are Perl, Ruby, Python, PHP, etc.
x
Client-side scripting languages create the scripts that run on the client side (i.e. your
browser). These are sent from the server by server-side scripts. Some good examples
are JavaScript, jQuery, CSS etc.
x
Easy learning: The user can learn to code in scripting languages quickly, not much
knowledge of web technology is required.
x
Fast editing: It is highly efficient with the limited number of data structures and
variables to use.
x
Interactivity: It helps in adding visualization interfaces and combinations in web
pages. Modern web pages demand the use of scripting languages. To create enhanced
web pages, fascinated visual description which includes background and foreground
colors and so on.
x
Functionality: There are different libraries which are part of different scripting
languages. They help in creating new applications in web browsers and are different
from normal programming languages.
x
Scripting languages are used in system administration. For example: Shell, Perl,
Python scripts etc.
x
It is used in Games application and Multimedia.
x
It is used to create plugins and extensions for existing applications.
JavaScript
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first
appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of
the language has been embedded in Netscape, Internet Explorer, and other web browsers.
The ECMA-262 Specification defined a standard version of the core JavaScript language.
x
JavaScript is a lightweight, interpreted programming language.
x
Designed for creating network-centric applications.
x
Complementary to and integrated with Java.
x
Complementary to and integrated with HTML.
x
Open and cross-platform.
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be
included in or referenced by an HTML document for the code to be interpreted by the
browser.
It means that a web page need not be a static HTML, but can include programs that interact
with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid e-
mail address in a form field.
In Java, all functions must belong to a class, and for this reason are called methods. In
JavaScript, a function does not have to belong to a particular object at all. When a function
does, however, it is often called a method. Functions and methods are both implemented in
the same way, using the function keyword. All methods are functions, but not all functions
are methods.
Unlike Java, JavaScript does not contain the idea of classes. Instead, JavaScript has
constructors, which are a special kind of function that directly creates objects. These
constructor functions define the state variables which each object holds and initialises their
values. These variables are often called the object's properties. Constructor functions also
supply objects with their methods.
In JavaScript, functions are themselves a special kind of object called Function Objects.
Function Objects can be called just as normal functions in other languages, but because they
are objects they can themselves be stored in variables and can be easily passed around as, say,
arguments to other functions. They can also contain properties of their own.Constructor
functions have a special Prototype property which is used to implement inheritance, as will
be explained later in the chapter on objects. Constructor functions are called using the new
keyword when creating objects.
JavaScript gives web developers a programming language for use in web pages & allows
them to do the following:
x
JavaScript gives HTML designers a programming tool
x
JavaScript can be used to validate data
x
JavaScript can read and write HTML elements
x
Create pop-up windows
x
Perform mathematical calculations on data
x
React to events, such as a user rolling over an image or clicking a button
x
Retrieve the current date and time from a useís computer or the last time a document
was modified
x
Determine the userís screen size, browser version, or screen resolution
x
JavaScript can put dynamic text into an HTML page
x
JavaScript can be used to create cookies
Advantages of JavaScript:
x
Less server interaction
x
Immediate feedback to the visitors
x
Increased interactivity
x
Richer interfaces
x
Web surfers donít need a special plug-in to use your scripts
x
Java Script is relatively secure.
Limitations of JavaScript:
x
Client-side JavaScript does not allow the reading or writing of files. This has been
kept for security reason.
x
JavaScript cannot be used for networking applications because there is no such
support available.
x
JavaScript doesn't have any multithreading or multiprocessing capabilities.
x
If your script doesnít work then your page is useless.
Points to remember:
1.
JavaScript is case-sensitive
2.
Each line of code is terminated by a semicolon
3.
Scripts require neither a main function nor an exit condition. There are major
differences between scripts and proper programs. Execution of a script starts with the
first line of code & runs until there is no more code
JavaScript comments:
In JavaScript, each line of comment is preceded by two slashes and continues from that point
to the end of the line.
Let us take a sample example to print out "Hello World". We added an optional HTML
comment that surrounds our JavaScript code. This is to save our code from a browser that
does not support JavaScript. The comment ends with a "//-->". Here "//" signifies a comment
in JavaScript, so we add that to prevent a browser from reading the end of the HTML
comment as a piece of JavaScript code. Next, we call a function document.write() which
writes a string into our HTML document.
This function can be used to write text, HTML, or both. Take a look at the following code.
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Hello World!")
//-->
</script>
</body>
</html>
This code will produce the following result:
Hello World!
Having written some JavaScript, we need to include it in an HTML page. We canít execute
these scripts from a command line, as the interpreter is part of the browser. The script is
included in the web page and run by the browser, usually as soon as the page has been
loaded. The browser is able to debug the script and can display errors.
If we are writing small scripts, or only use our scripts in few pages, then the easiest way is to
include the script in the HTML code. The syntax is shown below:
<html>
<head>
<script language=íjavascriptí>
<!--
JavaScript code here
//-->
</head>
<body>
ÖÖ
</body>
</html>
If we use lot of scripts, or our scripts are complex then including the code inside the web
page will make the source file difficult to read and debug. A better idea is to put the
JavaScript code in a separate file and include that code in the HTML file. By convention,
JavaScript programs are stored in files with the .js extension.
<html>
<head>
<script language=îjavascriptî src=îsample.jsî> </script>
</head>
<body>
ÖÖ
</body>
</html>
prompt(ìstringî) displays a prompt window with field for the user to enter a text string
Example:
<html>
<head>
<script language="javascript">
function show_alert()
{
alert("Hi! This is alert box!!");
}</script>
</head>
<body>
<input type="button" onclick="show_alert()" value=ìDisplay alert box" > </input>
</body>
</html>
JavaScript Programming Elements
Like any programming language, JavaScript has variables. A variable is a name assigned to
computer memory location to store data. As the name suggests, the value of the variable can
vary, as the program runs. We can create a variable with the var statement:
var <variablename> = <some value>;
Example:
var sum= 0;
var str;
We can initialize a variable like this:
str = ìhelloî;
# They must begin with a letter, digit or underscore character # We can.t use spaces in names
# Variable names are case sensitive # We can.t use reserved word as a variable name.
. Most high-level languages, including C and Java, are strongly typed. That is, a variable must
be declared before it is used, and its type must be included in its declaration. Once a variable is
declared, its type cannot be changed.
. As the JavaScript isweakly typed language, data types are not explicitly declared.
Example: var num;
num= 3;
num = "San Diego";
First, when the variable num is declared, it is empty. Its data type is actually the type undefined.
Then we assign it to the number 3, so its data type is numeric. Next we reassign it to the string
"San Diego", so the variable.s type is now string.
Example:
<html>
<body>
<script language=îjavascriptî type=îtext/javascriptî>
var s;
s = ìHelloî;
alert(typeof s);
s = 54321;
alert(typeof s);
</script> </body> </html>
DATATYPES
ï These types are referred to as primitive types because they are the basic building blocks from
which more complex types can be built.
ï Of the five, only number, string, and boolean are real data types in the sense of actually
storing data.
ï Undefined and null are types that arise under special circumstances.
Numeric Data Type:
.These are numbers and can be integers (such as 2, 22 and 2000) or floating-point values (such
as 23.42, -56.01, and 2E45).
Decimal: The usual numbers which are having the base 10 are the decimal numbers
Octal: Octal literals begin with a leading zero, and they consist of digits from zero through
seven. The following are all valid octal literals:
00 0777 024513600
HexaDecimal: Hexadecimal literals begin with a leading 0x, and they consist of digits from 0
through 9 and letters A through F. The following are all valid hexadecimal literals:
0x0 0XF8f00 0x1a3C5e7
Infinity, -Infinity Number too large or too small All infinity values compare
to represent equal to each other
NaN Undefined Operation NaN never compares equal to
anything, even to itself
Operators in JavaScript
.Arithmetic operators
.Relational operators
.Logical operators
.Assignment operators
Arithmetic operators:
Note: If the arguments of + are numbers then they are added together. If the arguments are
strings then they are concatenated and result is returned.
Example:
<html>
<body>
<script language="JavaScript">
<!-var
a = 5;
++a;
alert("The value of a = " + a );
-->
</script>
</body>
</html>
txt1="Welcome";
txt2="to L&T Infotech Ltd.!";
txt3=txt1 + " " + txt2;
(or)
txt1="Welcome ";
txt2="to CMRCET.!";
txt3=txt1 + txt2;
Relational operators/Comparison operators: Relational operators are used to compare
quantities.
Conditional Operator: Conditional operator is one the JavaScript.s comparison operator, which
Syntax :
<html>
<head>
<title>Operator Example</title>
</head>
<body>
<script language="JavaScript">
<!-var
userID ;
var password;
userID = prompt("Enter User ID"," ");
password = prompt("Enter Password"," ");
if(userID == "user" && password == "secure")
alert("Valid login");
else
alert("Invalid login");
-->
</script>
</body>
</html>
Assignment Operators: are used to assign the result of an expression to a variable.
STATEMENTS
Programs are composed of two things : data and code (set of statements) which manipulates the
data. Java script Statements can be divided into the following categories:
ñ Conditional Statements
ñ Looping Statements
ñ Jumping Statements
Conditional statements: Conditional statements are used to make decisions.
Various conditional statements in JavaScript:
Simple if
if-else Statement
nested if
else-if ladder
Example:
<html>
<body>
<script language=ìjavascriptî>
Syntax
switch (expression)
{
case label1: block1
break;
case label2: block2
break;
Ö.
Example:
<html>
<body>
<script language=ìjavascriptî>
ï for loop
ï while loop
ï do-while loop
for loop syntax:
<html>
<body>
<script language=ìjavascriptî>
for-in loop:
The for-in loop has a special use to enumerate all the properties contained within an object. This
loop is rarely used in regular JavaScript.
Example: Display window object properties
var i, a = ìî;
for( i in window)
a += i+ ìÖî;
alert(a);
while loop: executes the statements as long as the condition is true.
Syntax: while(condition)
{
Set of statements
}
Example:
<html>
<body>
<script language=ìjavascriptî>
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>
do-while syntax:
do
{
Set of statements
}while(condition);
Jumping Statements:
break statement:
break statement is used to terminate a loop, switch, or label statement.
When we use break without a label, it terminates the innermost enclosing while, do-while, for, or
switch immediately and transfers control to the following statement.
When we use break with a label, it terminates the specified labeled statement
Syntax:
ñ
break;
ñ
break label;
continue statement:
When we use continue without a label, it terminates the current iteration of the innermost
enclosing while, do-while or for statement and continues execution of the loop with the next
iteration.
When we use continue with a label, it applies to the looping statement identified with that label.
Syntax:
ñ
continue;
ñ
continue label;
WORKING WITH ARRAYS
An array is an ordered set of data elements which can be accessed through a single variable
name. In many programming languages arrays are contiguous areas of memory which means that
the first element is physically located next to the second and so on. In JavaScript, an array is
slightly different because it is a special type of object and has functionality which is not normally
available in other languages.
Basic Array Functions: The basic operations that are performed on arrays are creation, addition
of elements (inserting elements), accessing individual elements, removing elements.
Creating Arrays: We can create arrays in several ways:
<script language="javascript">
var a = [1,2,3];
var s = "";
for(var i=0;i<a.length;i++)
{
s += a[i] + " ";
}
alert(s);
</script>
What happens if we want to add an item to an array which is already full? Many languages
struggle with this problem. But JavaScript has a really good solution: the interpreter simply
extends the array and inserts the new item.
undefined.
Modifying array elements:
Searching an Array:
To search an array, simply read each element one by one & compare it with the value that we are
looking for.
JavaScript doesn.t provide a builtin function to remove array element. To do this, we can use the
following approach:
Note: The statement delete a[0] makes the value of a[0] undefined
OBJECT-BASED ARRAY FUNCTIONS:
In JavaScript, an array is an object. So, we can use various member functions of the object to
manipulate arrays.
concat()
The concat() method returns the array resulting from concatenating argument arrays to the array
on which the method was invoked. The original arrays are unaltered by this process.
Syntax: array1.concat(array2 [, array3,ÖarrayN]);
Example:
<script language="javascript">
var a = [1,2,3];
var b = ["a","b"];
alert(a.concat(b));
</script>
join()
join() method allows to join the array elements as strings separated by given specifier.The
original array is unaltered by this process.
Syntax: arrayname.join(separator);
Example:
<script language="javascript">
var a = [1,2,3];
alert(a.join(ì#î));
</script>
push()
push() function adds one or more elements to the end of an array and returns the last element
added.
Syntax: arrayname.push(element1 [, element2, ..elementN] );
Example:
<script language="javascript">
var a = [1,2,3];
alert(a.push(4,5)); //displays 5
alert(a); //displays 1,2,3,4,5
</script>
pop()
pop() removes the last element from the array and returns that element
Syntax: arrayname.pop();
reverse()
reverse() method transposes the elements of an array: the first array element becomes the last
and the last becomes the first. The original array is altered by this process.
Syntax: arrayname.reverse();
Example:
<script language="javascript">
var a = [1,2,3];
a.reverse();
alert(a);
</script>
shift()
shift() removes the first element of the array and in doing so shortens its length by one. It returns
the first element that is removed.
Ex: var a = [1, 2, 3];
var first = a.shift();
alert(a); // 2,3
alert(first); //1
unshift()
unshift() adds one or more elements to the front of an array.
Syntax: arrayname.unshift(element1 [ , element2, ..elementN] );
Example:
var a = ["x","y","z"];
a.unshift("p","q");
alert(a); //p,q,x,y,z
slice()
slice() returns a ìsliceî (subarray) of the array on which it is invoked. The method takes two
arguments, the start and end index, and returns an array containing the elements from index
start up to but not including index end. If we specify only first parameter, then array containing
the elements from start to the end of the array are returned. The original array is unaltered by
this
process.
Syntax: arrayname.slice( startindex , endindex);
Example:
splice()
The splice() method can be used to add, replace, or remove elements of an array in place. Any
elements that are removed are returned. It takes a variable number of arguments, the first two
arguments are mandatory. The original array is altered by this process.
Syntax : arrayname.splice(start, deleteCount, replacevalues);
# The first argument start is the index at which to perform the operation.
# The second argument is deleteCount, the number of elements to delete beginning with index
start. If we don.t want to delete any elements specify this value as 0.
# Any further arguments represented by replacevalues (that are comma-separated, if more than
one) are inserted in place of the deleted elements.
Example:
Example2:
var a = [80,732,450];
a.sort();
alert(a); //450,732,80
******************************************************************************
****
STRINGS
String is a set of characters enclose in a pair of single quotes or double quotes. In JavaScript
using string object, many useful string related functionalities can be done. Some commonly used
methods of string object are concatenating two strings, converting the string to uppercase or
lowercase, finding the substring of a given string and so on.
PROPERTY:
length
This method returns the index of substring found in the main string. If the substring is not found
returns -1. By default the indexOf() function starts index 0, however, an optional offset may be
specified, so that the search starts from that position.
Example: ìcmrcetî.indexOf(ìsvî);
ìDepartment of CSEî.indexOf(ìCSî,5);
lastIndexOf(substring [,offset])
This method returns the index of substring found in the main string (i.e. last occurence). If the
substring is not found returns -1. By default the lastIndexOf() function starts at index
string.length-1, however, an optional offset may be specified, so that the search starts from that
position in backwards.
This method is used to concatenate strings together. For example, s1.concat(s2) returns the
concatenated string of s1 and s2. The original strings don.t get altered by this operation.
substring(start [,end] )
This method returns the substring specified by start and end indices (upto end index, but not the
character at end index). If the end index is not specified, then this method returns substring from
substr(index [,length])
This method returns substring of specified number of characters (length), starting from index.
If the length is not specified it returns the entire substring starting from index.
toLowerCase( )
returns the string in lower case. The original string is not altered by this operation.
Example: <script language="javascript">
var s="CMRcet";
alert(s.toLowerCase());
alert(s); /
</script>
toUpperCase( )
returns the string in upper case. The original string is not altered by this operation.
alert(s.toUpperCase()); //displays
alert(s);
</script>
split(separator [,limit] )
Splits the string based on the separator specified and returns that array of substrings. If the limit
var s="vit#svecw#bvrice#sbsp";
var t =s.split("#");
alert(t);
</script>
Example2: <script language="javascript">
var s="cse#ece#mech#it";
var t =s.split("#");
alert(t); //displays cse,ece,mech,it
</script>
Write Javascript that determines whether the given string is palindrome or not
<html>
<body>
<script language="javascript">
var s = prompt("enter any string");
var n = s.length;
var flag=true;
for(var i=0; i<n;i++)
{
if(s.charAt(i) != s.charAt(n-1-i))
{
flag=false; break;
}
}
if(flag) alert("palendrome");
else alert("not palendrome");
</script>
</body>
</html>
string.anchor(ìanchornameî) string.link(url)
string.blink( ) string.big( )
string.bold( ) string.small( )
string.fixed( ) string.strike( )
string.fontcolor(colorvalue) string.sub( )
string.fontsize(integer 1 to 7) string.sup( )
string.italics( )
Example: <script language="javascript">
var s = "Test".bold(); //s value is: <b>Test</b>
document.write(s);
document.write("<br>");
document.write("CMRCET".italics());
</script>
FUNCTIONS
A function is a piece of code that performs a specific task. The function will be executed by an
event or by a call to that function. We can call a function from anywhere within the page (or
even from other pages if the function is embedded in an external .js file). JavaScript has a lot of
builtin functions.
Defining functions:
JavaScript function definition consists of the function keyword, followed by the name of the
function.
A list of arguments to the function are enclosed in parentheses and separated by commas. The
statements within the function are enclosed in curly braces { }.
Syntax:
function functionname(var1,var2,...,varX)
{
some code
}
Parameter Passing:
Not every function accepts parameters. When a function receives a value as a parameter, that
value is given a name and can be accessed using that name in the function. The names of
parameters are taken from the function definition and are applied in the order in which
parameters are passed in.
ï Primitive data types are passed by value in JavaScript. This means that a copy is made of a
variable when it is passed to a function, so any manipulation of a parameter holding primitive
data in the body of the function leaves the value of the original variable untouched.
ï Unlike primitive data types, composite types such as arrays and objects are passed by reference
rather than value.
In JavaScript parameters are passed as arrays. Every function has two properties that can be used
to find information about the parameters:
functionname.arguments
functionname.arguments.length
This is the number of parameters that have been passed into the function
Example:
<html>
<body>
<script language="javascript">
function fun(a,b){
var msg = fun.arguments[0]+".."+fun.arguments[1]; //referring a,b values
alert(msg);
}
fun(10,20); //function call
fun("abc","vit"); //function call
</script>
</body>
</html>
Returning values
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:
function prod(a,b)
{
x=a*b; return x;
}
Scoping Rules:
Programming languages usually impose rules, called scoping, which determine how a variable
can be accessed. JavaScript is no exception. In JavaScript variables can be either local or global.
global
Global scoping means that a variable is available to all parts of the program. Such variables are
declared outside of any function.
local
Local variables are declared inside a function. They can only be used by that function.
GLOBAL FUNCTIONS
EXCEPTION HANDLING
Runtime error handling is vitally important in all programs. Many OOP languages provide a
mechanism for handling with general classes of errors. The mechanism is called Exception
Handling.
try-catch block
The block of code that might cause the exception is placed inside try block. catch block contains
statements that are to be executed when the exception arises.
try { statement one
statement two
statement three
} catch(Error) { //Handle errors here } finally { // execute the code even regardless of above
catches are matched }
try{
}
catch(exception)
{
throw statement
The throw statement allows us to create an exception. If we use this statement together with the
try...catch statement, we can control program flow and generate accurate error messages.
Syntax
throw(exception)
Example:
} else if(isNaN(x)) { throw "Error! The value is not a number"; } } catch(er) { alert(er); }
</script> </body> </html>
The DOM defines what properties of a document can be retrieved and changed, and the methods
that can be performed. (or)
The Browser DOM specifies how JavaScript (and other programming languages) can be used to
access information about a document. Then you can perform calculations and decisions based
on the values retrieved from the document using JavaScript
Example: We can retrieve properties such as the value of the height attribute of any image, the
href attribute of any link, or the length of a password entered into a text box in a form.
Meanwhile, methods allow us to perform actions such as reset() or submit() methods on a form
that allows you to reset or submit a form.
DOM Hierarchy
. The objects in the web page follow a strict hierarchy, where thewindow object is the very top
level. Because window is the top level ìrootî object it can be omitted in the address syntax. For
instance, the window.document.bgColor property, which stores the value of the window.s
current background color, can be addressed simply as document.bgColor
. Several of the DOM objects have properties that contain an array of elements in that web
page. For example, with document.images[], the images[] array is a property of the document
object that will store the URL address of each image contained on that web page.The URL of the
first image in the HTML code is stored in the array at document.images[0]
BUILT-IN OBJECTS IN JAVASCRIPT
Javascript has many built-in objects which posses the capability of performing many tasks.
Hence sometimes Javascript is referred to as an Object based programming language.
Now we will discuss few commonly used objects of javascript along with their attributes &
behaviors.
array of frames stored in the order in which they are defined in the document
frames.length
number of frames
self
current window
opener
parent
status
defaultStatus
name
the name of the window if it was created using the open( ) method and a name was specified
location
this object contains the full URL address of the document that is currently loaded in the browser,
and assigning a new value to this will load the specified URL into the browser.
A typical URL address may comprise these parts:
window.location.href
window.location.protocol
window.location.host
window.location.pathname
window.location.hash
history
The window.history object contains history (i.e. array of URL addresses previously visited
during a browser session). For security reasons, these are not directly readable but they are used
to navigate back to previous pages. The back( ) and forward( ) methods of the window.history
object emulate the browser.s Back and Forward buttons. More flexible navigation is often
Example:
<html>
<head>
<script language="javascript">
function fun()
{
var n = prompt("enter any number");
window.history.go(n);
}
</script>
</head>
<body>
<form>
<h1>CMRCET</h1>
<h2>Medchal</h2>
<input type="button" value="navigate" onclick=fun()>
</form>
</body>
</html>
onload
This object can be used to specify the name of a function to be called immediately after a
document has completely loaded in the browser
Example:
<html>
<head>
<script language="javascript">
window.onunload=fun;
function fun(){
alert("number of frames = " + window.frames.length);
}
</script>
</head>
<frameset rows="30%,30%,*">
<frame name="row1" src="page1.html">
<frame name="row2" src="page2.html">
<frame name="row3" src="page3.html">
</frameset>
</html>
onunload
This object can be used to specify the name of a function to be called when the user exits the
web
page.
METHODS:
alert(ìstringî)
confirm(ìstringî)
prompt(ìstringî)
displays a prompt window with field for the user to enter a text string
blur( )
focus( )
scroll(x,y)
move the current window to the chosen x,y location
close( )
A document is a web page that is being either displayed or created. The document has a number
of properties that can be accessed by JavaScript programs and used to manipulate the content of
the page.
PROPERTIES:
bgColor
Example: write a javascript that designs 3 buttons ìredî, ìgreenî, and ìyellowî. When ever the
title
location
This object contains the full URL address of the document that is currently loaded in the
browser, and assigning a new value to this will load the specified URL into the browser.
Example:
<html>
<body>
<script language="javascript">
document.title="cmrcet";
function fun(){
document.location="page1.html";
}
</script>
<input type="button" value="change url" onclick="fun()">
</body>
</html>
lastModified
Object that provides information about date and time when a webpage was last modified. This
data is usually supplied to document.lastModified from the HTTP file header that is sent by the
web server
Example:
<html>
<body>
<script language="javascript">
window.status = "Last updated " + document.lastModified;
</script>
<h1> CMRCET</h1>
CMRCET was established in the year 2002.
</body>
</html>
linkColor, vlinkColor,alinkColor
These can be used to set the colors for the various types of links
forms[] array of forms on the current page
forms.length
links[]
array of links in the current page in the order in which they appear in the document
anchors[]
an array of anchors. Any named point inside an HTML document is an anchor. Anchors are
create using <a name=Ö>. These will be commonly used for moving around inside a large page.
The anchors property is an array of these names in the order in which they appear in the HTML
document. Anchors can be accessed like this: document.anchors[0]
images[]
an array of images
applets[]
an array of applets
cookie
Methods:
write(ìstringî)
writeln(ìstringî)
write a string to the HTML document and terminate it with a newline character. HTML pages
can be created on the fly using JavaScript. This is done using the write or writeln methods of the
document object.
Example:
document.write(ì<body>î);
document.write(ì<h1>CMRCET</h1>î);
document.write(ì<form>î);
clear()
close()
getElementById()
This object is used to obtain the date and time. This date and time is based on computer.s local
time (system.s time) or it can be based on GMT. This GMT is also known as UTC i.e. Universal
Method
getTime()
getDate()
getUTCDate()
getDay()
getUTCDay()
getHours()
getUTCHours()
getMinutes
getUTCMinutes()
getSeconds()
getUTCSeconds()
getMilliseconds()
getUTCMilliseconds()
setDate(value)
setHour(hr,min,sec,ms)
Example:
<html>
<head>
<title>Date Object</title>
</head>
<body>
<script type="text/javascript">
var d = new Date();
Meaning
MATH OBJECT
For performing the mathematical computations there are some useful methods available from
math object.
ï
sqrt(num)
ï
abs(num)
ï
ceil(num)
ï
floor(num)
ï
log(num)
ï
pow(a,b)
ï
min(a,b)
ï
max(a,b)
ï
sin(num)
ï
cos(num)
ï
tan(num)
ï
exp(num)
ï
asin(value)
ï
acos(value)
ï
atan(value)
random() -returns a psuedorandom number between 1 to 1
round(value)
In addition to the above methods, it has several properties (Numeric constants) like:
Math.E Euler constant
Math.PI 3.14159
Math.SQRT_2 The square root of 2
Math.SQRT1_2 The square root of Ω
Math.LN2 Log of 2
Math.LN10 Log of 10
Example:
<html>
<body>
<script language="javascript">
var n = prompt("enter any number");
alert("square root is "+Math.sqrt(n));
</script>
</body>
</html>
Exercise1:
1.Write a JavaScript program that generates the following table for the given value of n
Number Square
11
24
39
4 16
<html>
<body>
<table border=1>
<tr> <th>Number <th>Square </tr>
<script language="javascript">
var n = prompt("enter n");
for(i=1;i<=n;i++)
{
document.write("<tr><td>"+i+"<td>"+(i*i)+"</tr>");
}
</script>
</table>
</body>
</html>
FORM OBJECT
The window.document.forms object contains an array of all the forms in a HTML document,
indexed in the order in which they appear in the HTML code.
For example, window.document.forms[0] addresses the first form to appear in the HTML code
of a web page.
If the id attribute of the <form> element has been assigned a value, then the form can be
addressed by name.
For example, a form named reg can be addressed as document.forms.reg
All the attributes assigned in the <form> tag can be accessed as properties of that form object.
Example:
<html>
<head>
<script language=îjavascriptî>
window.onload = fun;
function fun()
{
Form elements:
The elements of the form are held in the array window.document.forms[].elements[]
The properties of the form elements can be accessed and set using Javascript.
The elements of the form are held in the array window.document.forms[].elements[]
The properties of the form elements can be accessed and set using Javascript.
Example1:
<html>
<head>
<script language="javascript">
function fun(){
var msg = "Element type: " + document.forms.reg.elements[0].type;
msg += "\nElement value: " + document.forms.reg.elements[0].value;
window.alert(msg);
}
</script>
</head>
<body>
<form id="reg">
<input type="button" value="click" name="btn1" onClick="fun()">
</form>
</body>
</html>
Example2:
<!--It is useful to change the label that is displayed on a button by its value attribute if that
button performs dual actions
-->
<html>
<head>
<script language="javascript">
var running=false; var num=0;
var tim;
function startstop(){
running = !running; count();
document.forms[0].btn1.value = (running) ? "stop" : "start";
}
function count(){
if(running){
num++;
window.status = "seconds elapsed: " + num;
tim = setTimeout("count()", 1000);
}
else{
num=0; clearTimeout(tim);
}
}
</script>
</head>
<body>
<form>
<input type="button" value="start" name="btn1" onClick="startstop()">
</form>
</body>
</html>
method
action
target
if specified this is the target window for responses to the submission of the form
elements[]
an array containing the form elements in the order in which they are declared in the document
length
Methods:
submit()
reset()
resets the form i.e. form controls will be set to default values
Radio Buttons
<html>
<head>
<script language="javascript">
function radio_info()
{
var msg="1st radio value = " + document.forms[0].rbnBranch[0].value;
msg += "\n 2nd radio value = " + document.forms[0].rbnBranch[1].value;
msg += "\n 3rd radio value = " + document.forms[0].rbnBranch[2].value;
msg += "\n 4th radio value = " + document.forms[0].rbnBranch[3].value;
alert(msg);
}
</script>
</head>
<body>
<form id="form1">
The branches in our college are: <br>
<input type="radio" name="rbnBranch" value="cse" selected>CSE<br>
<input type="radio" name="rbnBranch" value="it">IT<br>
<input type="radio" name="rbnBranch" value="ece">ECE<br>
<input type="radio" name="rbnBranch" value="eee">EEE<br><br>
<input type="button" value="Get Radio Info" onclick="radio_info()">
</form>
</body>
</html>
Radio Polling: The important feature of a radio button is whether it is checked or not. This can
be ascertained from the radio button.s checked property. It will return true, if the button is
checked otherwise false.
<html>
<head>
<script language="javascript">
function radio_info()
{
var msg="1st radio status = " + document.forms[0].rbnBranch[0].checked;
msg += "\n 2nd radio status = " + document.forms[0].rbnBranch[1].checked;
msg += "\n 3rd radio status = " + document.forms[0].rbnBranch[2].checked;
msg += "\n 4th radio status = " + document.forms[0].rbnBranch[3].checked;
alert(msg);
}
</script>
</head>
<body>
<form id="form1">
The branches in our college are: <br>
<input type="radio" name="rbnBranch" value="cse" selected>CSE<br>
<input type="radio" name="rbnBranch" value="it">IT<br>
<input type="radio" name="rbnBranch" value="ece">ECE<br>
<input type="radio" name="rbnBranch" value="eee">EEE<br><br>
<input type="button" value="Get Radio Info" onclick="radio_info()">
</form>
</body>
</html>
Check Boxes
Example:
<html>
<head>
<script language="javascript">
function info()
{
var msg="1st radio status = " + document.forms[0].branch[0].checked;
msg += "\n 2nd radio status = " + document.forms[0].branch[1].checked;
msg += "\n 3rd radio status = " + document.forms[0].branch[2].checked;
msg += "\n 4th radio status = " + document.forms[0].branch[3].checked;
alert(msg);
}
</script>
</head>
<body>
<form id="form1">
The branches in our college are: <br>
<input type="checkbox" name="branch" value="cse">CSE<br>
<input type="checkbox" name="branch" value="it">IT<br>
<input type="checkbox" name="branch" value="ece">ECE<br>
<input type="checkbox" name="branch" value="eee">EEE<br><br>
<input type="button" value="Get Info" onclick="info()">
</form>
</body>
</html>
Option Lists
The <option> tag can be used in the <select> tag to specify various options in the drop down
menu list.All menu items are stored in the <select> object.s options[] array. We can use the
selectedIndex property of option list to identify the index of the selected item
Example:
<html>
<head>
<script language="javascript">
function get_selected(){
var s = document.forms[0].sltVehicle.selectedIndex;
document.forms[0].txtVehicle.value = document.forms[0].sltVehicle.options[s].text;
}
</script>
</head>
<body>
<form name="form1">
<select name="sltVehicle">
<option value="v"> Volvo </option>
<option value="s" selected> Saab </option>
<option value="m"> Mercedes </option>
<option value="a"> Audi </option>
</select>
<input type="button" value="Show Selected" onClick="get_selected()">
<input type="text" size=15 name="txtVehicle">
</form>
</body>
</html>
<html>
<head>
<script language="javascript">
var exp="";
function fun(ch){
if(ch=='=') {
calc.txt1.value=eval(exp); exp = "";
}
else{
exp = exp + ch; calc.txt1.value=exp;
}
}
</script>
</head>
<body>
<form name="calc">
<table border=1>
<tr>
<th colspan=3>Simple calculator</th>
</tr>
<tr>
<th colspan=3><input type="text" name="txt1" size=15></th>
</tr>
<tr>
<td><input type="button" value="1" onclick="fun('1')"></td>
<td><input type="button" value="2" onclick="fun('2')"></td>
<td><input type="button" value="3" onclick="fun('3')"></td>
</tr>
<tr>
<td><input type="button" value="4" onclick="fun('4')"></td>
<td><input type="button" value="5" onclick="fun('5')"></td>
<td><input type="button" value="6" onclick="fun('6')"></td>
</tr>
<tr>
<td><input type="button" value="7" onclick="fun('7')"></td>
<td><input type="button" value="8" onclick="fun('8')"></td>
<td><input type="button" value="9" onclick="fun('9')"></td>
</tr>
<tr>
<td><input type="button" value="+" onclick="fun('+')"></td>
<td><input type="button" value="-" onclick="fun('-')"></td>
<td><input type="button" value="=" onclick="fun('=')"></td>
</tr>
</table>
</form>
</body>
</html>
No two browser models will process our javascript in the same way. Its important that we find
out which browser is being used to view our page. Then we can make a choice from our visitors:
.
Redirect them to a non-scripted version of our site
.
Present scripts that are tailored to suit each browser
Properties:
Navigator.appCodeName. The internal name for the browser. For both major products,this is
Mozilla, which was the name of the original Netscape code source
navigator.appName. public name of the browser
navigator.appVersion.the version number, platform on which the browser is running
navigator.userAgent. appCodeName + appVersion
navigator.platform. platform in which browser in running
navigator.plugins[] . array containing details of installed plugins
navigator.mimeTypes. array of all supported MIME types. Useful to make sure that the browser
can handle our data
Methods:
navigator.javaEnabled() .This method returns true or false depending upon whether java is
enabled or not in the system
Example:
<html>
<head>
<script language="javascript">
function fun()
{
if(navigator.javaEnabled()) window.location = "appletpage.html";
else window.location = "nonapplet.html";
}
</script>
</head>
<body>
Vishnu Institute of Technology was established in the year 2008 with four branches. For further
details visit our <a href="javascript:fun()" > website </a>
</body>
</html>
COOKIES
.
Cookies are small bits of key-value pair information that a Web server sends to a browser
through HTTP response and that the browser later returns unchanged through HTTP
Request when visiting the same Web site or domain.
.
A cookie is a small piece of information that is passed back and forth in the HTTP
request and response. The cookie sent by a servlet to the client will be passed back to the
server when the client requests another page from the same application.
.
Cookies are tiny files that can be written by javascript to store small amounts of data on
the local hard drive. There are limitations to the use of cookies that restrict their size to 4
kilobytes and web browsers are not required to retain more than 20 cookies per web
server. Typically a cookie may often retain user data for use across web pages or on
subsequent visits to a web site
.
Depending on the maximum age of a cookie, the Web browser either maintains the
cookie for the duration of the browsing session (i.e., until the user closes the Web
browser) or stores the cookie on the client computer for future use. When the browser
requests a resource from a server, cookies previously sent to the client by that server are
returned to the server as part of the request formulated by the browser. Cookies are
deleted automatically when they expire (i.e., reach their maximum age).
Benefits of Cookies:
.
Identifying a user during an e-commerce session
.
Remembering usernames and passwords : Cookies let a user log in to a site
automatically, providing a significant convenience for users of unshared computers.
.
Customizing sites: Sites can use cookies to remember user preferences.
.
Focusing advertising: Cookies let the site remember which topics interest certain users
and show advertisements relevant to those interests.
.
Security Issue: Browsers generally only accept 20 cookies per site and 300 cookies total,
and since browsers can limit each cookie to 4 kilobytes, cookies cannot be used to fill up
someone's disk or launch other denial-of-service attacks.
History:
Cookies were originally invented by Netscape to give 'memory' to web servers and browsers.
The HTTP protocol, which arranges for the transfer of web pages to your browser and browser
requests for pages to servers, is state-less, which means that once the server has sent a page to a
browser requesting it, it doesn't remember a thing about it. So if you come to the same web page
a second, third, hundredth or millionth time, the server once again considers it the very first time
you ever came there.
This can be annoying in a number of ways. The server cannot remember if you identified
yourself when you want to access protected pages, it cannot remember your user preferences, it
cannot remember anything. As soon as personalization was invented, this became a major
problem.
Cookies were invented to solve this problem. There are other ways to solve it, but cookies are
easy to maintain and very versatile.
A cookie is nothing but a small text file that's stored in your browser. It contains some data:
name-value
Each cookie has a name-value pair that contains the actual information. The name of the cookie
is for your benefit, you will search for this name when reading out the cookie information.
Expiry date
Each cookie has an expiry date after which it is trashed. If you don't specify the expiry date the
cookie is trashed when you close the browser. This expiry date should be in UTC (Greenwich)
time.
Domain and path
Each cookie also has a domain and a path. The domain tells the browser to which domain the
cookie should be sent. If you don't specify it, it becomes the domain of the page that sets the
cookie.
document.cookie
Cookies can be created, read and erased by JavaScript. They are accessible through the property
document.cookie. Though you can treat document.cookie as if it's a string, it isn't really, and you
have only access to the name-value pairs.
If I want to set a cookie for this domain with a name-value pair 'ppkcookie1=testcookie' that
expires in seven days from the moment I write this sentence, I do
document.cookie='ppkcookie1=testcookie; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'
Event Handling
An event is defined as ìsomething that takes placeî and that is exactly what it means in web
programming as well.
An event handler is JavaScript code that is designed to run each time a particular event occurs.
Handling Events
There are two ways to set and execute the JavaScript event handler for an HTML tag:
onmouseout="changeimage(2)" >
img.src = ìflower.jpg";
}
function changeimageout()
{
img.src = ìimg.jpg";
}
</script>
Example:
<html>
<head>
<script language="javascript">
function change(v)
{
var i = document.getElementById("mouse");
if(v==1) i.src="over.gif";
else i.src="out.gif";
}
</script>
</head>
<body>
<form name="form1">
<h1>Demonstrating Rollover Buttons</h1>
<img id="mouse" src="out.gif" width=100 height=100 onMouseOver=change(1)
onMouseOut=change(0)>
</form>
</body>
</html>
A Regular expression is a way of describing a pattern in a piece of text. It.s an easy way of
A regular expression is a JavaScript object. We can create regular expressions in one of two
ways.
.
Static regular expressions
Ex: var regex = /fish/fowl/ ;
.
Dynamic regular expressions
ï Simple patterns are constructed of characters for which we want to find a direct match.
ï For example, the pattern /abc/ matches character combinations in strings only when exactly the
characters 'abc' occur together and in that order.
ï Such a match would succeed in the strings
"Hi, do you know your abc's?ì
ï When the search for a match requires something more than a direct match, such as finding one
or more b's, or finding white space, the pattern includes special characters.
ï For example, the pattern /ab*c/ matches any character combination in which a single 'a' is
followed by zero or more 'b's (* means 0 or more occurrences of the preceding item) and then
immediately followed by 'c'. In the string "cbbabbbbcdebc," the pattern matches the substring
'abbbbc'
Regular expression patterns in java script must begin and end with forward slashes.
^ circumflex operator
\w Alphanumeric character
\D Alphabetic characters
\d Numeric chacters
\S All pritable characters
\s white space characters
\W Any character that is not an alphanumeric character
\b Backspace character