Java Script: Introduction To Javascript
Java Script: Introduction To Javascript
Java Script: Introduction To Javascript
Introduction to JavaScript
JavaScript is used in Web pages to improve the design, validate forms, and much more.
JavaScript was developed by Netscape and it is the most popular scripting language on the internet. It is
a lightweight interpreted programming language initially called LiveScript, which quickly evolved into
what is now JavaScript.
JavaScript is an untyped language, which means that variables do not have to a type specified.
JavaScript works in all major browsers that are version 3.0 or higher.
What is JavaScript?
JavaScript Java
JavaScript are interpreted by the browser. Java Programs are compiled on the server but run
on the client. Otherwise called Compiler Language
JavaScript is objected-based. There are no classes. Java is Object-oriented. It employs classes and
There is no inheritance. inheritance.
Variable data types not declared (loose typing) Variable data type must be declared (Strong
Dynamic Binding. Object references checked at typing) Static Binding. Object references must exist
runtime. at compile time.
Script Limited to browser functions Stand-alone Applications.
JavaScript is integrated and embedded in HTML Java is compiled into “applets” that are accessed
from HTML pages
Created by Netscape Corporation Created by Sun Microsystems.
Purpose of Scripting
1. Form Validation
2. Page embellishment, including rollover buttons and animation.
3. Dynamic Page generation
4. Making Pages interactive
Client-side JavaScript
Embedded in HTML on client side and the output result is client-side JavaScript. The two
browsers, Netscape Navigator(version 3.0 and above) and Internet Explorer(version 3.0 and above).
Support client-side JavaScript.
Server-Side JavaScript
Server side JavaScript environment allows you to use scripts to build web based applications
that are controlled by the Web Server. It provides an alternative of CGI(Common Gateway Interface) is
directly within HTML pages intermixed with web content.
Whenever a document containing server-side JavaScript code is requested by the client, the
server executes the script or scripts contained in the document and send the resulting document to the
requester.
Server-side JavaScript communicating with client accessing files on the server and connecting to
the Databases.
Ex: ASP(Active Server Page) from Microsoft, JSP(Java Server Page) from Sun Microsystems.
<script type=”text/javascript”>
(or)
<script language=”JavaScript”>
We can apply the script in both HEAD and BODY Tag. If we apply script in HEAD tag we can executing a
script by calling a function. When we apply script to the BODY tag it shows the content of the web page.
document.write(“String”)
<html>
<head>
<title>First</title>
<script type="text/javascript">
function display()
{
document.write("Welcome")
</script>
</head>
<body onload=display()>
</body>
</html>
<html>
<head>
<title>Second</title>
</head>
<body>
<script type="text/javascript">
document.write("Welcome")
</script>
</body>
</html>
To simplify this you can write a script in an external file, and save it with a .js file extension.
Example(test.js)
ExternalJS.html
<html>
<head>
<title>External JavaScript</title>
</head>
<body>
<script src="test.js"></script>
</body>
</html>
Statements
Statements are simply commands that perform a certain purpose. Several statements are built
into JavaScript; these are used to test variables, control the flow of the program, and perform actions.
Comments
Values
The value of each variable depends on the context in which it is assigned types.
The initial value of the property is usually specified by the VALUE attribute of FORM element.
Ex:
today=new date();
document.myform.date.value=today;
Literal:
Literals are numbers or strings used to represent fixed values in JavaScript. They are don’t
change during the execution of your scripts.
Variables
Variables are named containers that can hold a value. A variable value can change during the
script.
Rules
Declare a variable
variable_name=value;
Ex: i=10;
Ex:
var wheels=18;
wheels=18;
Datatypes
The scope of a variable refers to the areas within a program where a variable can be referened:
1) Local scope – A variable declared within a function with the var keyword is local to that
function. Other functions can’t access it. Variables used to store the function’s parameters are
also local to that function.
2) Global scope – A variable declared outside of a function, or without var keyword in a function, is
global; all JavaScript statements in the current HTML or script file can access the value.
Integers
An integer is simply a number that does not include a decimal. Integers in JavaScript can be only
positive numbers. You can use an integer as a literal in JavaScript simply by including the number.
JavaScript considers any number without a leading zero to be a decimal(base 10) number. You
can also use data in hexadecimal(base 16) and octal(base 8).
Floating-point numbers
Unlike integers, floating-point values can be either positive or negative. Any number without a
negative sign is assumed to be positive.
Boolean Values
Boolean values are the simplest data type. They can contain one of two values: true or false.
Because they can represent an on/off or 1/0 state, these are sometimes called binary values.
Boolean values are most commonly used as flags; variables that include whether a condition is
true or not.
Strings
Another important type of value in a JavaScript program is a string. Strings are simply groups of
characters. You can enclose a string enclosing them in double or single quotation marks.
“This is a string.”
‘A’
’25 pounds’
“200”
Special Characters
Along with alphanumeric characters, you can use a variety of special characters in JavaScript
strings. These include carriage returns, tabs and other nonprintable characters. To use a special
character we use backslash(\) followed by the code for the character.
Creating an array
JavaScript does not support arrays a variables. Instead, they are handled as objects. You can
create an array by using the Array Object.
Once you define the array, you can access its elements by using brackets [ ] to indicate the
index.
Ex: scores[0]=50;
scores[1]=98;
Unicode
In the string object’s characters processing methods, it include the charCodeAt() method, which
return the Unicode value of the character at the specified position. If there is no character at that index,
it return NaN(not a number).
Expression
By combining the variables and literal values to form a complex expression. The tools you use to
create an expression are operators.
Operators
-> Operator is a symbol that is used to perform the Mathematical and Logical operation.
Types
1) Unary Operators
2) Binary Operators
1) Unary Operators
-> It hold only one operand(variable) to perform the operation.
Types
++variable;
--variable;
Program
<html>
<head>
<title>Unary Operators</title>
</head>
<body>
<script type="text/javascript">
a=10;
document.write("++a="+(++a)+"<br>");
document.write("--a="+(--a)+"<br>");
document.write("a++="+(a++)+"<br>");
document.write("a--="+(a--)+"<br>");
document.write("a="+a);
</script>
</body>
</html>
Types
Program
<html>
<head>
<title>Binary Operators</title>
</head>
<body>
<script type="text/javascript">
a=10,b=6;
document.write("Addition="+(a+b)+"<br>");
document.write("Subtraction="+(a-b)+"<br>");
document.write("Multiplication="+(a*b)+"<br>");
document.write("Division="+(a/b)+"<br>");
document.write("Modulo Division="+(a%b)+"<br>");
</script>
</body>
</html>
Program
<html>
<head>
<title>Logical Operators</title>
</head>
<body>
<script type="text/javascript">
a=10,b=20,c=5;
res=(a>b&&a>c);
document.write("result="+res+"<br>");
res=(a>b||a>c);
document.write("result="+res+"<br>");
res=!(a>b);
document.write("result="+res+"<br>");
</script>
</body>
</html>
Program
<html>
<head>
<title>Relational Operators</title>
</head>
<body>
<script type="text/javascript">
a=10,b=20;
c=a>b;
document.write("c="+c+"<br>");
c=a<b;
document.write("c="+c+"<br>");
c=a>=b;
document.write("c="+c+"<br>");
c=a<=b;
document.write("c="+c+"<br>");
c=a==b;
document.write("c="+c+"<br>");
c=a!=b;
document.write("c="+c);
</script>
</body>
</html>
<html>
<head>
<title>Bitwise Operators</title>
</head>
<body>
<script type="text/javascript">
a=5,b=8,c=0;
c=a&b;
document.write("c="+c+"<br>");
c=a|b;
document.write("c="+c+"<br>");
c=a^b;
document.write("c="+c+"<br>");
</script>
</body>
</html>
Program
<html>
<head>
<title>Bitwise Operators</title>
</head>
<body>
<script type="text/javascript">
a=5;
</body>
</html>
Formula
(i) Left Shift
Value*2n
(ii) Right Shift
Value*2-n
n – number of shift
(vi) Assignment Operator(=)
-> It is used to assign a value to the variable
variable=value (or) var variable=value;
Program
<html>
<head>
</head>
<body>
<script type="text/javascript">
a=10,b=5;
a+=b;
document.write("a="+a+"<br>");
a-=b;
document.write("a="+a+"<br>");
a*=b;
document.write("a="+a+"<br>");
a/=b;
document.write("a="+a+"<br>");
a%=b;
document.write("a="+a+"<br>");
</script>
</body>
</html>
(condition)?True_value:False_value;
Program
<html>
<head>
<title>Ternary Operator</title>
</head>
<body>
<script type="text/javascript">
a=100,b=15,big=0;
big=(a>b)?a:b;
document.write("big="+big);
</script>
</body>
</html>
Example:
Program
<html>
<head>
<title>Typeof Operator</title>
</head>
<body>
<script type="text/javascript">
a=100;
document.write("Type of a="+typeof(a)+"<br>");
document.write("Type of msg="+typeof(msg)+"<br>");
result=(10>20);
document.write("Type of result="+typeof(result));
</script>
</body>
</html>
Order of Precedence
The order of precedence determines the order in which the browser applies operators to
operands when evaluating an expression.
The order of precedence, from highest(perform first) to lower(perform last) is
Conditional Statements
Conditional Statements in JavaScript are used to perform different actions based on different
conditions. In JavaScript we have five conditional statements:
1. Simple if
2. if…else
3. if…else if…else
4. nested if
5. switch case
1. Simple if
-> It test the condition if it is true it execute a block of code. Otherwise it is skipped.
if(condition)
{
Statement(s);
}
if – keyword
Program
<html>
<head>
<title>Simple If</title>
</head>
<body>
<script type="text/javascript">
var n;
if(n<0)
</script>
</body>
</html>
(ii) if…else
-> It test the condition if it is true the True-Block Statement(s) are executed. Otherwise the else part ie
the False-Block Statement(s) are executed.
if(condition)
{
True-Block Statement(s);
}
else
{
False-Block Statement(s);
}
Program
<html>
<head>
<title>If Else</title>
</head>
<body>
<script type="text/javascript">
var n;
n=parseInt(prompt("Enter the number:",0,"input"))
if(n<0)
document.write('Number is Negative')
else
document.write('Number is Positive')
</script>
</body>
</html>
if(condition-1)
{
True-Block Statement(s)-1;
}
else if(condition-2)
{
True-Block Statement(s)-2;
}
.
.
.
else
{
False-Block Statement(s);
}
Program
<html>
<head>
</head>
<body>
<script type="text/javascript">
var a,b,c;
if(a>b&&a>c)
document.write('A is biggest')
else if(b>c)
document.write('B is biggest')
else
document.write('C is biggest')
</script>
</body>
</html>
(iv) nested if
-> An if consists of another if…else if…else ladder it is called nested if.
if(Main condition)
{
if(condition-1)
{
True-Block Statement(s)-1;
}
else if(condition-2)
{
True-Block Statement(s)-2;
}
.
.
else if(condition-n)
{
True-Block Statement(s)-n;
}
else
{
False-Block Statement(s);
}
}
Program
<html>
<head>
<title>Nested If</title>
</head>
<body>
<script type="text/javascript">
var a,b,c;
if(a>b)
if(a>c)
document.write('A is biggest')
else
document.write('C is biggest')
else if(b>c)
document.write('B is biggest')
else
{
document.write('C is biggest')
</script>
</body>
</html>
switch(expression)
{
case label-1:
Statement(s)-1;
break;
case label-2:
Statement(s)-2;
break;
.
.
.
case label-n:
Statement(s)-n;
break;
default:
Invalid Statement(s)-1;
break;
}
Program
<html>
<head>
<title>Switch Case</title>
</head>
<body>
<script type="text/javascript">
switch(day)
case 1:
document.write('Sunday')
break
case 2:
document.write('Monday')
break
case 3:
document.write('Tuesday')
break
case 4:
document.write('Wednesday')
break
case 5:
document.write('Thursday')
break
case 6:
document.write('Friday')
break
case 7:
document.write('Saturday')
break
default:
</script>
</body>
</html>
Looping statements in JavaScript are used to execute the same block of statement for a
specified number of times.
1. while
2. do…while
3. for
1. while
The while statement will execute a block of code while a condition is true.
while(condition)
{
Code to be executed
}
Program-1
<html>
<head>
<title>While Loop</title>
</head>
<body>
<script type="text/javascript">
i=1
while(i<=n)
document.write("CSC"+"<br>")
i++
</script>
</body>
</html>
Program-2
<html>
<head>
<title>While Loop</title>
</head>
<body>
<script type="text/javascript">
i=1
while(i<=n)
document.write(i+"<br>")
i++
</script>
</body>
</html>
2. do…while
The do…while statement will execute a block of code once, and then it will repeat the loop while
a condition is true.
do
{
Code to be executed
}while(condition);
Program
<html>
<head>
</head>
<body>
<script type="text/javascript">
i=1
do
document.write(i+"<br>")
i++
}while(i<=n);
</script>
</body>
</html>
4. for loop
The for statement will execute a block of code a specified number of times
Program
<html>
<head>
<title>For Loop</title>
</head>
<body>
<script language="JavaScript">
for(i=1,fact=1;i<=10;i++,fact*=i)
document.write(i+"!="+fact);
document.write("<br>");
</script>
</body>
</html>
The for…in Construct
The for..in loop is not as flexible as ordinary for or while loops; instead, it is specifically designed
to perform an operation on each property of an object.
for(variable in array|object)
{
Code to be executed
}
Program
<html>
<head>
</head>
<body>
<script language="JavaScript">
players=new Array()
players[0]="Sachin"
players[1]="Sehwag"
players[2]="Dhoni"
players[3]="Rohit"
players[4]="Kohli"
players[5]="Dawan"
for(i in players)
document.write(players[i]);
document.write("<br>");
}
</script>
</body>
</html>
There is one way out of an infinite loop. The break statement can be used during a loop to exit
the loop immediately and continue with the first statement after the loop:
Program
<html>
<head>
<title>Break Keyword</title>
</head>
<body>
<script language="JavaScript">
for(i=0;i<10;i++)
if(i==5)
break;
document.write(i);
document.write("<br>");
</script>
</body>
</html>
Program
<html>
<head>
<title>Continue Keyword</title>
</head>
<body>
<script language="JavaScript">
for(i=0;i<10;i++)
if(i%2!=0)
continue;
document.write(i);
document.write("<br>");
</script>
</body>
</html>
With Statement
The with statement is used to avoid repeatedly specifying the object reference when accessing
properties or methods of that object.
with(object)
{
Statements
}
Program
<html>
<head>
<title>With Statement</title>
</head>
<body>
<script language="JavaScript">
with(document)
write("hello");
</script>
</body>
</html>
Functions:
A function is a reusable code-block that will be executed by an event, or when the function is
called.
A function contains some code that will be executed by an event or a call to that function. A
function is a set of statements. You can reuse functions within the same script, or in other documents.
You define functions at the beginning of a file (in the head section), and call them later in the document.
How to Define a function
To create a function you define its name, any values as(“arguments”), and some statements.
function myfunction(argument1,argument2,…)
{
Some statements
}
Arguments are variables used in the function. The variable values are passed on by the function
call.
By placing functions in the head section of the document, you make sure that all the code in the
function has been loaded before the function is called.
A function is not executed before it is called. You can call a function containing arguments:
myfunction(argument1,argument2,etc)
Or without arguments:
myfunction()
Example Program
<html>
<head>
<title>Function</title>
<script type="text/javascript">
function greet(who)
</script>
</head>
<body>
<script type="text/javascript">
greet("CSC");
</script>
</body>
</html>
Functions that will return a result must use the “return” statement. This statement specifies the
value which will be returned to where the function was called from. Say you have a function that returns
the sum of two numbers:
function total(a,b)
{
result=a+b
return result
}
When you call this function you must send two arguments with it:
sum=total(2,3)
Program
<html>
<head>
<title>Returning Function</title>
<script type="text/javascript">
function total(a,b)
result=a+b
return result
</script>
</head>
<body>
<script type="text/javascript">
sum=total(2,3)
</body>
</html>
The arguments [] property of a function object refers to an array that contains the complete set
of argument values passed to the function. JavaScript allows any number of argument values to be
passed to any function with the number of argument names that appear in the function definition.
The arguments.length property count the number of arguments that we are passed in the
function.
Program
<html>
<head>
<title>Arguments Array</title>
<script type="text/javascript">
function f(x,y,z)
if(f.arguments.length!=3)
return null;
</script>
</head>
<body>
<script type="text/javascript">
f(2,3)
</script>
</body>
</html>
The JavaScript provides a number of built-in functions that are part of the language.
For example, the parseInt() function converts a string to an integer, and the Math.sin() function
computes the sine of a number.
JavaScript Objects
Functions are used to proved a uniform method for organizing code, Objects serve the same
purpose for data. Objects provide the ability to hold multiple values, so that a group of related data
elements can be associated with one another.
An object is a custom data type that can combine data with functions to act upon it. The data
items in an object are its properties, and the functions are its methods.
The bits of data stored in an object are called properties of the object. Each object can have one
or more properties or attributes. Properties can be numbers, strings, or even other objects. Each
property has a name associated with it, which you must use to refer to that property.
To illustrate object properties, let us take the example the String object. Any variable that
contains a string in JavaScript is actually a String object. The String object has a single property called
length (built-in object), which indicates the current length of the string. You can use two different types
of notation to refer to an object’s property.
The first and most common method is to separate the object name and property name with a
period (dot operator(.)).
For example, the following statement sets the variable len to the length of the address string
variable:
len=address.length;
Object can also include methods. There are functions that work with the objects data. For
example,
var StringVar=new String(“this is a string”);
var x=StringVar.length;
StringVar=StringVar.toUpperCase();
After executing this code, StringVar is a new variable with the value of “this is a string”.
The x variable is set of the length of the StringVar, it produce 16. Length is a property of String object.
The UpperCase() method converts all of the string to upper case. i.e “THIS IS A STRING”.
Object and arrays must be created with new operator. The new operator is to create a new
instance of an object or an array.
Syntax:
O=new Object();
Since objects are made up of methods(functions) and parameters(variables), the newly created
object “O” in this case has all of the same methods and parameters of the original object. The
parameters will all be set to their default value.
<html>
<head>
<title>Constructor</title>
<script type="text/javascript">
function Rectangle(w,h)
this.width=w;
this.height=h;
document.write("Area of Rectangle="+this.width*this.height+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
rect1=new Rectangle(2,4);
rect2=new Rectangle(8.5,11);
</script>
</body>
</html>
The Constructor performs its initialization on the object referred to by the this keyword.
A constructor will generally perform initialization based on the argument values that are passed to it.
Some constructors may also initialize other properties of a new object
The new operator actually creating an instance of an object class. Any variable you create with
the new keyword is an instance of that object. The object definition itself is referred to as the object
class, or the object type.
With some built-in objects, such as the String object, you don’t need to use the new keyword;
you simply define a string variable, and JavaScript creates a String object automatically.
It is simply shorthand for “the current object.” This is usually used in object definitions, where it
refers to the object being defined, and in method definitions, where it refers to the object the method is
acting on.
Example Program
<html>
<head>
</head>
<body>
<script language="JavaScript">
function mth(level)
html="H"+level;
text=this.toString();
start="<"+html+">";
stop="</"+html+">";
return start+text+stop;
String.prototype.heading=mth;
document.write("This is a test".heading(1));
</script>
</body>
</html>
Built-In Objects
JavaScript includes several built-in objects. They are not part of the object hierarchy, and they
do not represent any part of a web page. They are used for programming functions. The built-in
functions as follows:
Array Object
An Array object is used to store a set of values in a single variable name. Each value is an
element of the array and has an associated index number.
You can refer to a particular element in the array by using the name of the array and the index
number. The index number starts at zero.
You create an instance of the Array object with the “new” keyword.
The expected number of elements goes inside the parentheses, in this case 5.
You assign data to each of the elements in the array like this:
family_names[0]=”Tony”
family_names[1]=”Jani”
family_names[2]=”Gajini”
family_names[3]=”Bhaski”
family_names[4]=”Kai”
And the data can be retrieved from any element by using the index of the particular array element you
want. Like this:
mother=family_names[0]
father=family_names[1]
Methods Explanation
length – property Returns the number of elements in an array. This
property is assigned a value when an array is
created
concat() Returns an array concatenated of two arrays
join() Returns a string of all the elements of an array
concatenated together
reverse() Returns the array reversed
slice() Returns a specified part of the array
sort() Returns a sorted array
Example Program
<html>
<head>
<title>Array Object</title>
</head>
<body>
<script language="JavaScript">
var family_names=new Array();
family_names[0]="Tony";
family_names[1]="Jani";
family_names[2]="Gajini";
family_names[3]="Bhaski";
family_names[4]="Kai";
document.write("Family Names:<p>");
for(var i=0;i<family_names.length;i++)
document.write(i+1+"."+family_names[i]+"<br>");
joint_family[0]="Ram";
joint_family[1]="Suresh";
document.write("</p>");
</script>
</body>
</html>
The String object
Properties Explanation
length Returns the number of characters in a string
Methods Explanation
anchor() Returns a string as an anchor
big() Returns a string in big text
small() Returns a string as small text
blink() Returns a string blinking
bold() Returns a string in bold
italics() Returns a string in italic
strike() Returns a string strikethrough
charAt() Returns a character at a specified position
charCodeAt() Returns the Unicode of the character at a specified position
concat() Returns two concatenated strings
fixed() Returns a string as teletype
fontcolor() Returns a string in a specified color
fontsize() Returns a string in a specified font size
fromCharCode() Returns the character value of a Unicode
indexOf() Returns a position of the first occurrence of a specified string inside
another string. Returns -1 if it never occurs.
lastIndexOf() Returns the position of the first occurrence of a specified string inside
another string. Returns -1 if it never occurs. Note: This method starts from
right and moves left
link() Returns a string as a hyperlink
match() Similar to indexOf and lastIndexOf but this method returns the specified
string, or “null”, instead of a numeric value
replace() Replaces some specified characters with some new specified characters
search() Returns an integer if the string contains some specified characters if not it
returns -1
slice() Returns a string containing a specified character index
split() Splits a string into an array of strings
sub() Returns a string as subscript
sup() Returns a string as superscript
substr() Returns the specified characters. 14,7 returns 7 characters, from the 14th
character(starts at 0)
substring() Returns the specified characters 7,14 returns all characters from the 7th up
to but not including the 14th (starts at 0)
toLowerCase() Converts a string to lower case
toUpperCase() Converts a string to upper case
Program
<html>
<head>
<title>String Object</title>
</head>
<body>
<script language="JavaScript">
document.write("Length of s="+s.length+"<br>");
document.write("Anchor Text="+s.anchor()+"<br>");
document.write("Big Text="+s.big()+"<br>");
document.write("Small Text="+s.small()+"<br>");
document.write("Blink Text="+s.blink()+"<br>");
document.write("Bold Text="+s.bold()+"<br>");
document.write("Italic Text="+s.italics()+"<br>");
document.write("Strike Text="+s.strike()+"<br>");
document.write("Font Color(Green)="+s.fontcolor('green')+"<br>");
document.write("Font size(10)="+s.fontsize(10)+"<br>");
document.write("Link of S="+mylink.link("D:\\ANIMATION\\12g5.gif")+"<br>");
document.write("Match of C="+s.match('C')+"<br>");
document.write("Subscript="+s.sub()+"<br>");
document.write("Superscript="+s.sup()+"<br>");
document.write("substr="+s.substr(7,14)+"<br>");
document.write("substring="+s.substring(7,14)+"<br>");
</script>
</body>
</html>
The Date Object is used to work with dates and times. You create an instance of the Date object
with the “new” keyword.
After creating an instance of the Date object, you can access all the methods of the object from
the “my_date” variable. If, for example, you want to return the date (from 1-31)
my_date.getDate()
You can also write a date inside the parentheses of the Date() object, like this:
new Date(“Month dd, yyyy hh:mm:ss”)
new Date(yy,mm,dd,hh,mm,ss)
new Date(yy,mm,dd)
new Date(milliseconds)
Here is how you can create a Date Object for each of the ways above:
Methods Explanation
Date() Returns a Date Object
getDate() Returns the date of a Date object (from 1-31)
getDay() Returns the day of a Date object (from 0-6. 0=Sunday, 1=Monday,
etc)
getMonth() Returns the month of a Date object (from 0-11, 0=January,
1=February, etc)
getFullYear() Returns the year of a Date Object (Four Digits)
getYear() Returns the year of a date object (from 0-99). Use getFullYear
instead!!
getHours() Returns the hour of a Date object (from 0-23)
getMinutes() Returns the minute of a Date object (from 0-59)
getSeconds() Returns the second of a Date object (from 0-59)
getMilliseconds() Returns the millisecond of a Date object (from 0-999)
getTimezoneOffset() Returns the time difference between user’s computer and GMT
parse() Returns a string date value that holds the number of milliseconds
since January 01 1970 00:00:00
setDate() Sets the date of the month in the Date object (from 1-31)
setMonth() Sets the month in the Date object (from 0-11,
0=January,1=February etc)
setYear() Sets the year in the Date object (00-99)
setFullYear() Sets the year in the Date object (four digits)
setHours() Sets the hour in the Date object (from 0-23)
setMinutes() Set the minute in the Date object (from 0-59)
setSeconds() Sets the second in the Date object (from 0-59)
setTime() Sets the milliseconds after 1/1-1970
toGMTString() Converts the Date object to a string, set to GMT time zone
toLocaleString() Converts the Date object to a string, set to the current time zone
toString() Converts the Date object to a string
Program
<html>
<head>
<title>Date Object</title>
</head>
<body>
<script language="JavaScript">
document.write("Get Date="+my_date.getDate()+"<br>");
document.write("Get Day="+my_date.getDay()+"<br>");
document.write("Get Month="+my_date.getMonth()+"<br>");
document.write("Get Year="+my_date.getYear()+"<br>");
document.write("Get Hours="+my_date.getHours()+"<br>");
document.write("Get Minutes="+my_date.getMinutes()+"<br>");
document.write("Get Seconds="+my_date.getSeconds()+"<br>");
document.write("Get MilliSeconds="+my_date.getMilliseconds()+"<br>");
document.write("Get Time="+my_date.getTime()+"<br>");
//document.write("Parse="+my_date.parse("22-01-2019")+"<br>");
my_date2.setMonth(01);
my_date2.setYear(2019);
my_date2.setFullYear(2019);
my_date2.setHours(10);
my_date2.setMinutes(35);
my_date2.setSeconds(53);
document.write("My Date2="+my_date2+"<br>");
document.write("set Time="+my_date.setTime(19)+"<br>");
document.write("To GMTString="+my_date.toGMTString()+"<br>");
document.write("To LocaleString="+my_date.toLocaleString()+"<br>");
document.write("To String="+my_date.toString()+"<br>");
</script>
</body>
</html>
The built-in Math Object includes mathematical constants and functions. You do not need to
create the Math object before using it.
Properties Explanation
Math.E Euler’s constant (approximately 2.718281828459).
Math.LN2 The natural logarithm of 2 (approximately 0.6931471805599).
Math.LN10 The natural logarithm of 10 (approximately 2.302585092994).
Math.LOG2E The base 2 logarithm of Euler’s constant, e (approximately
1.442695040889).
Math.LOG10E The base 10 logarithm of Euler’s constant, e (approximately
0.4342944819033).
Math.PI The ratio of a circle’s circumference to its diameter (approximately
3.14159265359).
Math.SQRT1_2 The square root of one half (approximately 0.7071067811865).
Math.SQRT2 The square root of 2 (approximately 1.414213562373).
Math.abs(number) Returns the absolute value of number.
Math.cos(number) Returns the cosine of number.
Math.sin(number) Returns the sine of number.
Math.tan(number) Returns the tangent of number.
Math.acos(number) Returns the arc cosine, in radians of number. Returns 0 if number is out of
range.
Math.asin(number) Returns the arc sine, in radians, of number. Returns 0 if number is out of
range.
Math.atan(number) Returns the arc tangent, in radians, of number.
Math.ceil(number) Returns the greatest integer that is equal to or greater than number.
Math.floor(number) Returns the least integer that is equal to or less than number.
Math.exp(number) Returns the value of enumber. E is Euler’s constant-the base of the natural
algorithms.
Math.log(number) Returns the natural algorithm (base e) of number. If number is 0 or less
than 0, log returns -1.797693134862316e+308.
Math.max(number1, Returns the greater of number1 and number2.
number2)
Math.min(number1, Returns the lesser of number1 and number2.
number2)
Math.pow(base, Returns base exponent.
exponent)
Math.random() Returns a pseudo-random number between 0 and 1. Currently available on
UNIX platforms only.
Math.round(number) Returns the next higher integer value if the fractional part of number s .5
or greater. Returns the next lower integer value if the fractional part of
number is less than .5.
Math.sqrt(number) Returns the square root of number. sqrt() always returns 0 if number is out
of range.
Program
<html>
<head>
<title>Math Object</title>
</head>
<body>
<script language="JavaScript">
document.write("Math.E="+Math.E+"<br>");
document.write("Math.LN2="+Math.LN2+"<br>");
document.write("Math.LN10="+Math.LN10+"<br>");
document.write("Math.LOG2E="+Math.LOG2E+"<br>");
document.write("Math.LOG10E="+Math.LOG10E+"<br>");
document.write("Math.PI="+Math.PI+"<br>");
document.write("Math.SQRT1_2="+Math.SQRT1_2+"<br>");
document.write("Math.SQRT2="+Math.SQRT2+"<br>");
document.write("Math.abs(-125)="+Math.abs(-125)+"<br>");
document.write("Math.cos(60)="+Math.cos(60)+"<br>");
document.write("Math.sin(30)="+Math.sin(30)+"<br>");
document.write("Math.tan(45)="+Math.tan(45)+"<br>");
document.write("Math.acos(0.5)="+Math.acos(0.5)+"<br>");
document.write("Math.asin(0.5)="+Math.asin(0.5)+"<br>");
document.write("Math.atan(0.5)="+Math.atan(0.5)+"<br>");
document.write("Math.ceil(23.56928)="+Math.ceil(23.56928)+"<br>");
document.write("Math.floor(23.56928)="+Math.floor(23.56928)+"<br>");
document.write("Math.exp(0)="+Math.exp(0)+"<br>");
document.write("Math.log(2)="+Math.log(2)+"<br>");
document.write("Math.max(156,223)="+Math.max(156,223)+"<br>");
document.write("Math.min(156,223)="+Math.min(156,223)+"<br>");
document.write("Math.pow(2,5)="+Math.pow(2,5)+"<br>");
document.write("Math.random()="+Math.random()+"<br>");
document.write("Math.round(23.56928)="+Math.round(23.56928)+"<br>");
document.write("Math.sqrt(25)="+Math.sqrt(25)+"<br>");
</script>
</body>
</html>
<html>
<head>
<title>Random Number</title>
</head>
<body>
<h4>Random Numbers</h4>
<script language="JavaScript">
total=0;
for(i=0;i<5000;i++)
num=Math.random();
total+=num;
average=total/5000;
average=Math.round(average*1000)/1000;
</script>
</body>
</html>
The navigator object includes several properties that reflect information about the version of
Netscape in use. These are all read-only properties:
Program
<html>
<head>
<title>Navigator Object</title>
</head>
<body>
<script language="JavaScript">
document.write("Application Name="+navigator.appName+"<br>");
document.write("Application Version="+navigator.appVersion+"<br>");
</script>
</body>
</html>
Client-side JavaScript scripts are part of an HTML file, and are usually coded within the <SCRIPT>
and </SCRIPT> tags. Between these tags you may place any number of JavaScript statements, which will
be executed in the order they appear as part of the document loading process, <SCRIPT> tags may
appear in either the <HEAD> or <BODY> of an HTML document.
A single HTML document may contain more than one pair of (non-overlapping <SCRIPT> and
</SCRIPT> tags). These multiple separate scripts will have their statements executed in the order they
appear within the document. For example, you have the following script somewhere in an HTML page:
<SCRIPT type=”text/javascript”>
//JavaScript code goes here
</SCRIPT>
Or
<SCRIPT LANGUAGE=”JavaScript”>
//JavaScript code goes here
</SCRIPT>
JavaScript Files
A JavaScript file is just that pure JavaScript, without <SCRIPT> tags or any other HTML. A
JavaScript file typically has a .js extension.
The <SCRIPT> tag supports a new SRC attribute. The value of this attribute specifies the URL of a
file of JavaScript code. It is used like this:
<SCRIPT SRC=”../../javascript/util.js”></SCRIPT>
It simplifies your HTML files by allowing you to remove large blocks of JavaScript code from
them.
When you have functions or other JavaScript code used by several different HTML files, you can
keep it in a single file and read it into each HTML file that needs it. This reduces disk usage, and
makes code maintenance much easier.
When JavaScript functions are used by more than one page, placing them in a separate
JavaScript file allows them to be cached by the browser, making them load much more quickly.
<NOSCRIPT> tag
The <noscript> tag allows you to specify HTML that is to be displayed if JavaScript is turned off or not
supported by the browser.
Syntax:
<NOSCRIPT>
//message for turned-off or not supported browser
</NOSCRIPT>
Program
<html>
<head>
</head>
<body>
<script type="text/javascript">
</script>
<noscript>
</noscript>
</body>
</html>
The DOM (Document Object Model) defines and describes these objects, their properties and
methods.
The browser provides us with a series of object. The HTML page displayed by the browser is
known as document object.
Event Handlers
Events are often used to trigger portions of a program. In JavaScript, events pertain to the web
page containing the script. When the user clicks on a link, selects or enters text, or even moves the
mouse over part of the page, an event occurs.
The script that you use to detect and respond to an event is called an event handler.
For example, the following piece of HTML code creates a button with the words “Click me!”;
clicking the button runs an piece of JavaScript code that adds together two numbers and displays the
result in a dialog box.
<FORM>
<INPUT TYPE=”submit” VALUE=”Click me!” onClick=”var sum=1+2; alert(sum);”>
</FORM>
Types of Events
There are different types of events such as mouse event, keyboard event and onload event. Etc.,
in JavaScript. The Table below shows list the types of events and their uses.
Program
<html>
<head>
<title>JavaScript Events</title>
<script language="JavaScript">
function greeting()
}
function terminate()
if(conreturn)
window.close();
</script>
</head>
</body>
</html>
<html>
<head>
<title>JavaScript Events</title>
<script language="JavaScript">
function TextChange(text)
alert(text);
function describe(text)
window.status=text;
return true;
}
function clearStatus()
window.status=''
function Selected(text)
window.status='Selected Text:'+text;
</script>
</head>
<body>
<form>
<p>
<ul>
</ul>
</p>
</form>
</body>
</html>
One of the most powerful features of the web is the use of interactive forms. JavaScript allows
the user to enter information and interact with the site, by single most useful validating forms. This
means using a script to verify that the information you enter is valid by form-based objects, submit and
reset.
The submit Object. The submit button was originally intended in HTML to be the final button a
user would click to send a form back to the server. With JavaScript, you can now use this button to also
send all of the information collected in a form to another window on your browser, or to the same
window itself.
Syntax:
<INPUT TYPE=”submit” NAME=”submitName” VALUE=”buttonText” [onClick=”handlerText”]>
You access these object’s properties and methods by the following syntax:
submitName.propertyName
submitName.methodName(parameters)
formName.elements[index].propertyName
formName.elements[index].methodName(parameters)
When you click a submit button, it always loads a new page-even if that page is the same page you were
already on. The submit object uses the onClick event handler and can be clicked by using the
submitName.click method.
The reset Object. The reset button allows a user to completely reset a form’s input fields to
their defaults.
Syntax:
You access these object’s properties and methods by the following syntax:
resetName.propertyName
resetName.methodName(parameters)
formName.elements[index].propertyName
formName.elements[index].methodName(parameters)
The reset button uses the same onClick event handler and click method as the submit object.
<html>
<head>
<title>Form Validation</title>
<script language="JavaScript">
function validate()
if(document.form1.yourname.value.length<1)
return false;
if(document.form1.address.value.length<1)
return false;
if(document.form1.phone.value.length<1)
return false;
return true;
}
</script>
</head>
<body>
</form>
</body>
</html>
Document Properties
The Document object has a number of properties that correspond to attributes of the <BODY>
tag, and which are used to specify the colors that the document is displayed in.
Properties Explanation
title Specify the title of the web page
bgColor Specify the Background color of the document. The color value is either String or the
Hexadecimal digits (RRGGBB)
fgColor Specify the Foreground color of the text in document. The color value is either String or
the Hexadecimal digits (RRGGBB)
linkColor Specifies the color of the unvisited links
vlinkColor Specifies the color of the visited links
alinkColor Specifies the color of the activated links
lastModified Specify the date and time of the most recent change of the document.
Method Explanation
Write Display some text in the web page
Program
<html>
<head>
<title>Document Object</title>
</head>
<body>
<script type="text/javascript">
document.bgColor="orange"
document.fgColor="yellow"
document.linkColor="blue"
document.alinkColor="magenta"
document.vlinkColor="green"
</script>
</body>
</html>
Object Hierarchy
This hierarchy includes a variety of browser objects that represent data on the current web page
and in the current browser window.
The browser objects are arranged into a hierarchy of parent and child objects. When you refer
to an object, you use the parent object name followed by the child object names or names, separated by
periods. For example, JavaScript stores objects to represent images in a document as children of the
document object. The following refers to the image6 object, a child of the document object, which is a
child of the window object:
Window.document.image6
A diagram of the object hierarchy is given in Figure Below which serves as the parent object for most of
the other objects.
document links()
anchors()
Window
history
(parent, frames[],self,top)
images()
location
forms() form elements
The window object is at the top of the object hierarchy. A window object exists for each open
browser window. The properties of this object describe the document in the window and provide
information about the window. Three of the window object’s properties are child objects:
The location object stores the location (URL) that is displayed in the window.
The document object holds the web page itself.
The history object contains a list of sites visited before and after the current site.
Property Explanation
Name Return the name of the current window
Parent Return the parent window of the current window
Self Return the current window
Top Returns the topmost browser window
Status Change the status of the current window
Program
<html>
<head>
<title>Window Properties</title>
<script language="JavaScript">
function pageShow()
MyWin=window.open('MyWindow','_top','status=yes');
//MyWin=window.open('','MyWindow');
MyWin.document.write('Title='+MyWin.title+'<br>');
MyWin.document.write('Name='+MyWin.name+'<br>');
//window.location.href="WindowObject.html";
</script>
</head>
<body>
<form>
</form>
</body>
</html>
You can create a new browser window with the window.open() method enables you to open a
new browser window. A typical statement to open a new window looks like this:
WindowName=window.open(“URL”,”WindowName”,”Feature List”);
The features available in the third parameter of the window.open() method include width and height, to
set the size of the window, and several features that can be set to either yes(1) or no(0): toolbar,
location, directories, status, menubar, scrollbars, and resizable. You can list only the features you want
to change from the default. This example creates a small window with no toolbar or status line:
SmallWin=window.open(“”,”small”,width=100,height=120,toolbar=0,status=0);
Opening and Closing Windows
Of course, you can close windows as well. The window.close() method closes a window. Its main
purpose is for closing windows you have created. For example, this statement closes a window called
updatewindow:
updatewindow.close();
Program
<html>
<head>
</head>
<body>
<hr>
Use the buttons below to test opening and closing windows in JavaScript.
<hr>
<form name="winform">
<input type="button" value="Open a New Window"
onClick="NewWin=window.open('','self','toolbar=no,status=no,width=200,height=200');">
</form>
</body>
</html>
Displaying Dialogs
The window object includes three methods which are useful for displaying messages and
interacting with the user:
Method Explanation
alert() Displays an alert dialog box
confirm() Displays a confirmation dialog with OK and Cancel Button. If OK is Pressed return
true and false if Cancel is pressed.
prompt() Displays a message and prompts the user for input. It returns the text entered by
the user.
Program
<html>
<head>
</head>
<body>
<hr>
<hr>
<form name="winform">
</form>
</body>
</html>
Using Frames
Some browsers (including the latest Netscape and Microsoft browsers) support frames or
framesets. These enable you to divide the browser window into multiple panes, called frames. Each
frame can contain a separate URL or the output of a script.
When a window contains multiple frames, each frames is represented in JavaScript by a frame
object. This object is equivalent to a window object, but it is used for dealing with that frame. The frame
object’s name is the same the NAME attribute you give it in the <FRAME> tag.
The window and self keyword refer to the current window. Another keyword parent enables you
to refer to the main window. Each frame object in a window is a child of the parent window object.
Program
<html>
<head>
<title>Frame Tag</title>
</frameset>
</noframe>
</head>
</html>
This frame array stores information about each of the frames in the document. The frames are
indexed starting with zero and beginning with the first <FRAME> tag in the frameset document.
As an example, you could refer to the frames defined in above using array references:
Each frame object (or each member of the frames array) has two properties:
Program
<html>
<head>
<title>Frame Document</title>
</head>
<frameset cols="*,*">
</frameset>
</html>
Program: FrameNavigation.html
<html>
<head>
<title>Navigation Frame</title>
</head>
<body>
<ul>
</ul>
</body>
</html>
JavaScript URLs
Another way that JavaScript code can be included on the client side is in a URL following the
javascript:pseudo-protocol specifier.
The special protocol type specifies that the body of the URL is arbitrary JavaScript code to be
interpreted by the JavaScript interpreter. If the JavaScript code in a JavaScript URL contains multiple
statements, the statements must be separated from one another by semicolons. Such as URL might look
like the following:
When the browser “loads” one of these JavaScript URLs, it executes the JavaScript code
contained in the URL and displays the “document” referred to by the URL. This “document” is the string
value of the last JavaScript statement in the URL. This string will be formatted and displayed just like any
other document loaded into the browser.
More commonly, a JavaScript URL will contain JavaScript statements that perform actions but
return no value. For example:
javascript:alert(“Hello World!”)
When this sort of URL is “loaded,” the browser executes the JavaScript code, but, because there
is no value to display as the new document, it does not modify the currently displayed document.
Program
<html>
<head>
<title>Javascript URLs</title>
</head>
<body>
<script language="JavaScript">
javascript:alert("Hello World!")
</script>
</body>
</html>
A common use for graphics on the Web is in image maps-large images with clickable areas. Each
area can link to a separate page. There are two types of image maps:
Server-side image maps require a CGI script to interpret the user’s actions.
Client-side image maps are embedded in HTML, and require no interaction with the
server. This is a newer standard and not officially part of HTML, but it is supported by
most browsers.
The client-side image maps and JavaScript work well together. You can use client-side image
maps with JavaScript in three ways:
As with any link, you can link areas of the map to javascript: method URLs to execute
functions.
Each <AREA> tag, which defines a clickable area, can have event handlers:
onMouseOver, onMouseOut, and onClick. These function in the same way as the
corresponding link and image event handlers.
Each <AREA> tag is reflected in an area object. These objects are part of the links array,
and have the same properties.
As an example of using a client-side image map with JavaScript, let’s create a simple image map
menu for a fictional company.
Use your favorite graphics application to create the actual graphic as a GIF or JPEG image.
Create a MAP definition that describes areas in the image.
Include the image in the document, using the USEMAP attribute to point to the MAP definition.
Program
<html>
<head>
<script language="JavaScript">
function update(text)
document.form1.text1.value=text;
</script>
</head>
<body>
<map name="map1">
</map>
<hr>
Click on the image on the respective area of department and see the text box and status bar.
<hr>
<hr>
<form name="form1">
<b>Clicked Item:</b>
</form>
<hr>
</body>
</html>
Cookies
A cookie is a chunk of information sent by the server, which can be stored on the client. Cookies
are stored with a date they expire and the name of the host from which they came. When user
communicates with the same host later, the data is sent back.
Cookies can also be used in JavaScript. You can use them to store information between pages, or
event to store information on users’ computers to remember their preferences next time they load your
page.
The cookies are stored in a “cookie jar” on the user’s computer. Specifically, each cookie is a line
in a file called cookies.txt, usually in the same directory as Netscape itselt.
Cookies are stored for the current document; and they are accessed with the document.cookie
property. This property is a text value which can contain the following components:
name=value: A name and value, separated by the equal sign. This is the actual data
stored in the cookie.
expires=date: An expiration date. If this date is not included, the cookie is erased when
the user exits the browser. (For the format of the date)
domain=machine: The domain name for which the cookie is valid. By default, this is the
domain of the current page.
path=path: The URL path for which the cookie is valid. By default, this is the current URL.
Program
<html>
<head>
<script>
if(document.cookie.substring(0,2)!="n=")
document.cookie=" "+nam+";";
}
</script>
</head>
<body>
<hr>
<script>
indx=document.cookie.indexOf(";");
nam=document.cookie.substring(0,indx+1);
</script>
</body>
</html>
JAVA CONSOLE
Unlike JavaScript, Java code is never included in the HTML file itself. Instead, a special HTML tag,
<APPLET>, is used to embed the applet in the Web page. Here is a simple example of an applet:
<applet code=”Applet1.class” width=55 height=68></applet>
Notice that both opening and closing <APPLET> tags are required. Between them, you can use
optional <PARAM> tags to give parameters to the applet. The parameters required depend on the
applet. Each <PARAM> tag includes a variable name and value:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Font;
public class JavaTest extends Applet
g.setFont();
Example(Java1.html)
<html>
<head>
</head>
<body>
<h1>test</h1>
<hr>
<hr>
</applet>
</body>
</html>
In Netscape Navigator 3.0 and above introduced a new feature called LiveConnect. Which
provides the following capabilities:
JavaScript programs can communicate with and control Java applets.
Java applets can access JavaScript objects, properties and methods.
JavaScript programs can control Netscape plug-ins.
Each Java applet you embed in a Web page is made available to JavaScript as an applet object,
with the same name as the applet’s class name. The applet object resides in the object hierarchy under
the document object. For example, a Java applet called Scroll would be accessed through an object
called document.Scroll.
The objects, properties, and methods of the applet are then available to JavaScript, provided the
Java programmer has made them public.
Let’s create a Java applet that can be manipulated from within JavaScript. The below java
example shows the Java source code.
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Font;
String message;
message=msgText;
repaint();
g.setFont(f);
g.drawString(message,15,50);
This applet now includes a setMessage() method to change the text in the display. The below
HTML example shows the HTML and JavaScript document used to control the applet.
<html>
<head>
</head>
<body>
<hr>
The Java applet below displays text in a large font. You can enter new text to display in the form
below, and JavaScript will call the Java applet to change the text.
<hr>
<form name="form1">
<input type="text" name="text1">
</form>
<hr>
</applet>
<hr>
End of Page
</body>
</html>
This uses a simple event handler to call the Java applet’s setMessage() method. The string you
enter in the text field is passed to the applet and displayed in place of the original string.
It’s possible for a Java applet to do things you don’t want it to, so you must give permission for it
to access your JavaScript program and objects. To do this, add the MAYSCRIPT attribute to the
<APPLET> tag that embeds the applet:
<APPLET CODE=”Script.class” NAME=”TestApp” MAYSCRIPT>
</APPLET>
Steps for the Java Programmer
For the Java Programmer, there are also some important steps before you can access JavaScript.
First, you need to include the netscape.javascript package, which provides these functions, in your
imported classes:
import netscape.javascript.*
Next, you need to create a handle for the JavaScript window. To do this, define a variable of
type JSObject and use the getWindow method to assign it:
Once you have a handle for the JavaScript window, you can get the objects you need to access.
To do this, you need to call the getMember method for each property. For example, to make the text1
field on the form1 form accessible:
js=JSObject.getWindow(this);
JSObject document=(JSObject)js.getMember(“document”);
JSObject form1=(JSObject)document.getMember(“form1”);
JSObject text1=(JSObject)form1.getMember(“text1”);
You are creating an object of type JSObject for the document, then for each object underneath it.
You can also call JavaScript functions and methods from within Java, using the same technique.
The two methods you use for this purpose are call and eval. For example, this statement calls a
JavaScript method to display an alert message:
js=JSObject.getWindow(this);
js.call(“window.alert(‘This is a test.’);”);
--END--