Sie sind auf Seite 1von 31

1

Java Script is one popular scripting language over internet. Scripting means a small
sneak (piece). It is always independent on other languages.
There are no relationship between in java & java script. Java Script is a
scripting language that always dependent in HTML language. It used to css
commands. It is mainly used to creating DHTML pages & validating the data. This
is called client side validations.

Oops: - Inheritance, polymorphism, abstraction, encapsulation etc...


 Java script is object based oriented language.
Inheritance is does not support in JavaScript, so it is called object based
oriented language.
 JavaScript was developed by Netscape (company name) & initially called live
script. Later Microsoft developed and adds some futures live script then it is called
“Jscript”. Jscript is nothing but Java script. We cannot create own classes in java
script.
Java script is designed to add interactivity to HTML pages. It is usually
embedded directly into html pages.
Java script is mainly useful to improve designs of WebPages, validate from data
at client side, detects (find) visitor’s browsers, create and use to cookies, and much
more.
Java script is also called light weight programming language, because Java
script is return with very simple syntax. Java script is containing executable code.
Java script is also called interpreted language, because script code can be
executed without preliminary compilation.

Creating a java script: - html script tag is used to script code inside the html page.
<script> </script>
The script is containing 2 attributes. They are
1) Language attribute: - It represents name of scripting language such as
JavaScript, VbScript.
<script language=“JavaScript”>
2) Type attribute: - It indicates MIME (multi purpose internet mail extension) type
of scripting code. It sets to an alpha-numeric MIME type of code.
<script type=“text / JavaScript”>

Location of script or placing the script: - Script code can be placed in both head &
body section of html page.
Script in head section Script in body section
<html> <html>
<head> <head>
<script type=“text / JavaScript”> <script type= “text / JavaScript”>
Script code here </script>
</script> </head>
3

</head> <body>
<body> Script code here
</body> </body>
</html> </html>
Scripting in both head & body section: - we can create unlimited number of scripts
inside the same page. So we can locate multiple scripts in both head & body section
of page.
Ex: -
<html>
<head>
<script type=“text / JavaScript”>
Script code here
</script>
</head>
<body>
<script type=“text / JavaScript”>
Script code here
</script>
</body>
</html>

Program: -
<html>
<head>
<script language="JavaScript">
document.write("hai my name is Sudheer Reddy")
</script>
</head>
<body text="red">
<marquee>
<script language="JavaScript">
document.write("hai my name is Sunil Kumar Reddy")
</script> </marquee>
</body>
</html>

O/P: -
hai my name is Sudheer Reddy
hai my name is Sunil Kumar Reddy
document. write is the proper name of object.
 There are 2 ways of executing script code
1) direct execute
2) to execute script code dynamically
3)
Reacts to events: - JavaScript can be set to execute when something happens. When
the page is finished loading in browser window (or) when the user clicks on html
element dynamically.
4

Ex: -
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional // EN">
<HTML>
<HEAD>
<script language="JavaScript">
function myf( )
{
document.write("Hai Sudheer")
}
</script>
</HEAD>
<BODY>
to execute script code:
<input type="button" value="click me" onclick="myf( )">
To execute script code:
<input type="button" value="touch me" onmouseover="myf( )">
</BODY>
</HTML>
O/P: - to execute script code: To execute script code:

Creating external script: - some times you might want to run same script on several
pages without having to write the script on each page. To simplify this, write
external script & save .js extension. To use external script specify .js file in src
attribute of script tag.
Note: - external script can not contain script tag.
document.write("this is external script code 1 "+"<br>");
document.write("this is external script code 2 "+"<br>");
document.write("this is external script code 3 "+"<br>");
document.write("this is external script code 4 ");

save: - external.js

 <HTML>
<BODY>
<script language="JavaScript">
document.write("this is document code 1 "+"<br>");
document.write("this is document code 2 "+"<br>");
</script>
<script src="external.js">
</script>
</BODY>
</HTML>

O/P: -
this is document code 1
this is document code 2
5

this is external script code 1


this is external script code 2
this is external script code 3
this is external script code 4

JavaScript syntax rules: - JavaScript is case sensitive language. In this upper case
lower case letters are differentiated (not same).
Ex: - a=20;
A=20;
Those the variable name ‘a’ is different from the variable named ‘A’.
Ex: - myf( ) // correct
myF( ) // incorrect
 ; is optional in general JavaScript.
Ex: - a=20 // valid
b=30 // valid
A=10; b=40; // valid

However it is required when you put multiple statements in the same line.
 JavaScript ignore white space. In java script white space, tag space & empty
lines are not preserved.
 To display special symbols we use \.

Comment lines: - comments lines are not executable.


// single line comment
/* this is multi line comment */

Declaring variable: - variable is a memory location where data can be stored. In


java script variables with any type of data are declared by using the keyword ‘var’.
All keywords are small letters only.
var a; a=20;
var str; str= “Sunil”;
var c; c=’a’;
var d; d=30.7;
But the keyword is not mandatory when declare of the variable.
c;  not valid. In this solution var keyword must be declared.
 During the script, we can change value of variable as well as type of value of
variable.
Ex: -
a=20;
a=30.7;

Operators: - when ever you combined operators & operands then it is called
operation. There are 3 types of operators.
1) Unary operator: - if operator acts upon single operand then it I called unary
operator.
2) Binary operator: -if operator acts upon two operands then it I called binary
operator.
6

3) Ternary operator: - if operator acts upon three operands then it I called


ternary operator.

1) Arithmetic operators: - + , - , * , / , % , ++ , --
a=20;
- a; // - operator act upon only single operand, so it is called unary operator.
a=20;
b=40;
a - b; // - operator act upon only single operand, so it is called binary
operator.
*, / , %  pure binary operators.

2) Assignment operators: -
= is 1st category  it assigns variables.
+ = , - = , * = , / = , % =  2nd category.
These sets of operators are compound assignment operators & combine
couple of the statements.
a = a + b; a+=b; // both are same.

3) Relational operators: - < , > , > = , < = , = =


! = = , = = = , ! = = = (newly defined)
When you compare two quantities, we can use relational operators.
*Ex: -
a=20;
b=“20”;
a==b returns true
a===b  returns false.
Because = = checks only content of variable, = = = checks both data & type of
data of variable in java script.

4) Logical operators: - && , || , !


Compare two or more quantities we can use logical operators. These
operators are just like boolean (true / false)

((cond1)&&(cond2)&&(cond3))
All conditions must be true it is true otherwise false.
((cond1)||(cond2)||(cond3))
Any one condition is true it is true otherwise false.

5) Conditional operators: - : , ?
var1=(cond)?var2:var3
Ex: - a=20; b=30;
big=(a>b)?a:b
document.write(big)

6) New operator: - new operator is creating one object dynamically.


var obj=new classname( )
7

Ex: - var d=new Date( );


d.getMonth( );

Conditional statements: -
In Java Script conditional statements are useful to excuse different action for
different decisions (conditions).
1) if statement.
2) if-else statement.
3) switch statement.

 if statement is useful to perform(execute) a single statement or group of


statements when the condition is true.
 if – else statement is useful to execute a one block of code from two blocks
where one condition.
 Switch statement is very frequently to select one of many blocks of code for
execution.

Ex: -
<HTML>
<BODY>
<script language="JavaScript">
var d=new Date( );
var day=d.getDay( );
switch(day)
{
case 0:
document.write("enjoy Sunday");
break;
case 1:
document.write("learning Monday");
break;
case 2:
document.write("popper Tuesday");
break;
case 3:
document.write("middle Wednesday");
break;
case 4:
document.write("temple Thursday");
break;
case 5:
document.write("finally Friday");
break;
case 5:
document.write("super Saturday");
break;
default :
8

document.write("I am looking forward for this week end");


}
</script>
</BODY>
</HTML>

O/P: - learning Monday

Control structures :-( loops)


In java script loops are useful to perform one block of code repeatedly for specified
no of times. There are 3 types of loops.
1) while loop
2) do-while loop
3) for loop.

1) while loop:- while loop is useful to execute a block of code repeatedly bussed on
condition. It is also entry controlled loop.
Syntax: - while(cond) { --- }
Ex: - <HTML>
<HEAD>
<TITLE> Natural No's up to 100 using while </TITLE>
</HEAD>
<BODY>
<script language="JavaScript">
a=1;
while(a<=100)
{
document.write(a+" ");
a++;
}
</script>
</BODY>
</HTML>

O/P: - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

2) do-while loop: - do-while loop is useful to execute a block of code repeatedly


based on condition. It is also called exit controlled loop.
Syntax: - do { --- } while(cond);
Ex: - <HTML>
<HEAD>
<TITLE> Fibonacci series up to 10 </TITLE>
</HEAD>
<BODY>
9

<script language="JavaScript">
a=0;
b=1;
document.write( a+" "+b+" ")
c=2;
do
{
s=a+b;
document.write( s+" ");
c++;
a=b;
b=s;
}
while (c<10);
</script>
</BODY>
</HTML>

O/P: - 0 1 1 2 3 5 8 13 21 34

3) for loop: -
Syntax: - for(initialization; cond; (inc / dec)) { ------ }
Ex: - <HTML>
<HEAD>
<TITLE> Prime no's up to 100 </TITLE>
</HEAD>
<BODY>
<script language="JavaScript">
for(i=0;i<=100;i++)
{
c=0;
for(j=0;j<=i;j++)
{
if(i%j==0)
c++;
}
if(c==2)
document.write( i+" ");
}
</script>
</BODY>
</HTML>

O/P: - 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

 JavaScript comes with many utility classes, that stores different types of data,
but we should create object to the class before using it.
10

1) String class: - It is used to store text String that lets you to do process on it. There
are 2 ways to store that string as shown below
1) var str=“Sunil”
2) var str=new String(“Sunil”)

 String object contains so many methods & properties.


Representation: Objname.method( )

Method Description
big( ) displays a string in a big font.
small( ) displays a string in a small font.
blink( ) displays a blinking string.
bold( ) displays a string in bold.
italics( ) displays a string in italic.
fontsize( ) displays a string in specific size.
fixed( ) displays a string in specific size.
fontcolor( ) displays a string in specified color.
strike( ) displays a string with a strike through.
sub( ) displays a string as a subscript.
sup( ) displays a string as a super script.
toLowerCase( ) displays a string in lower case letters.
toUpperCase( ) displays a string in upper case letters.
charAt( ) returns the character at a specified position.
concat( ) join 2 or more strings.
indexOf( ) returns the position of the 1st occurrence of a
specified string value in a string.
lastIndexOf( ) returns the position of the last occurrence of a
specified string value searching backwards
from the specified position in a string.
link( ) displays a string as a hyper link.
match( ) searches for a specified string value in a string
and return sub string.
replace( ) replace some characters with some other
characters in a string.
search( ) searches a string for a specified value.
slice( ) extracts a part of a string add returns the
extracted part in a new string.
spilt( ) splits a string in an array of strings.
substr( ) extracts a specified a number characters in a
string from a start index.
subString( ) extracts the character in a string between two
specified indices.

Property Description
length returns the no. of characters in a string.

Ex: -
11

<HTML>
<HEAD>
<TITLE> String class</TITLE>
</HEAD>
<BODY>
<script language="JavaScript">
var t=new String("P.Sudheer Reddy")
var s=new String("P.Sunil Kumar Reddy")
document.write("<p>"+"Small = "+t.small( )+"</p>")
document.write("<p>"+"Blink = "+t.blink( )+"</p>")
document.write("<p>"+"Bold = "+t.bold( )+"</p>")
document.write("<p>"+"Italics = "+t.italics( )+"</p>")
document.write("<p>"+"Font size = "+t.fontsize(20)+"</p>")
document.write("<p>"+"Fixed = "+t.fixed( )+"</p>")
document.write("<p>"+"Font color = "+t.fontcolor("red")+"</p>")
document.write("<p>"+"strike = "+t.strike( )+"</p>")
document.write("<p>"+"Sub class = "+t.sub( )+"</p>")
document.write("<p>"+"Super Class = "+t.sup ( )+"</p>")
document.write("<p>"+"Lower case = "+t.toLowerCase( )+"</p>")
document.write("<p>"+"Upper case = "+t.toUpperCase( )+"</p>")
document.write("<p>"+"Char at = "+t.charAt( )+"</p>")
document.write("<p>"+"Concat = "+t.concat( )+"</p>")
document.write("<p>"+"Index of = "+t.indexOf("Reddy")+"</p>")
document.write("<p>"+"Last index of ="+t.lastIndexOf("Sudheer")+"</p>")
document.write("<p>"+"Link = "+t.link("www.google.com")+"</p>")
document.write("<p>"+"Match = "+s.match("Sunil")+"</p>")
document.write("<p>"+"Replace = "+t.replace("sunil kumar reddy")+"</p>")
document.write("<p>"+"Search = "+t.search("Sudheer")+"</p>")
document.write("<p>"+"Slice = "+s.slice("Sudheer")+"</p>")
document.write("<p>"+"Split = "+t.split("Reddy")+"</p>")
document.write("<p>"+"Substr ="+t.substr("Sunil")+"</p>")
document.write("<p>"+"Substring = "+t.substring("Sunil")+"</p>")
</script>
</BODY>
</HTML>

O/P: - Small = P.Sudheer Reddy

Blink = P.Sudheer Reddy

Bold = P.Sudheer Reddy

Italics = P.Sudheer Reddy

Font size = P.Sudheer Reddy


Fixed = P.Sudheer Reddy
12

Font color = P.Sudheer Reddy

strike = P.Sudheer Reddy

Sub class = P.Sudheer Reddy

Super Class = P.Sudheer Reddy

Lower case = p.sudheer reddy

Upper case = P.SUDHEER REDDY

Char at = P

Concat = P.Sudheer Reddy

Index of = 10

Last index of = 2

Link = P.Sudheer Reddy

Match = Sunil

Replace = P.Sudheer Reddy

Search = 2

Slice = P.Sunil Kumar Reddy

Split = P.Sudheer ,

Substr =P.Sudheer Reddy

Substring = P.Sudheer Reddy

2) Defining Arrays:-
The array class is used to store a set of values in a single variable name with
unique index number. We can define an Array object with the operator new. There
are two ways of adding values to an array.
1) a) var myCars=new Array( );
myCars[0] = “Wagner”
myCars[1] = “innova”
myCars[2] = “Santro”
You called also pass an integer argument to control the array’s size.
b) var my cars =new Array(3)
myCars[0] = “Wagner”
13

myCars[1] = “innova”
myCars[2] = “santro”
2) var myCars = new Array ( “Wagner”, “innova”, “Santro”)
 Array object contains so many methods & properties.
Representation: Objname.method( )

Method Description
concat( ) joins 2 or more arrays and returns the result.
join ( ) puts all the elements of an array into a string. The elements
are separated by a specified delimiter.
pop( ) removes & return the last element of an array.
push( ) adds 1 or more elements to the end of an array & returns
the new length.
shift( ) removes & returns the first element of an array.
unshift( ) adds 1 or more elements to the beginning of an array &
returns the new length.
reverse( ) reverse the order of the elements in an array.
slice( ) returns selected element from an existing array.
sort( ) sorts the array elements of an array.
splice( ) removes & adds new elements to an array.

Property Description
length sets or return the no. of elements in an array.

Ex: -
<HTML>
<HEAD>
<TITLE> Array class </TITLE>
</HEAD>
<BODY>
<script language="JavaScript">
var a=new Array(3);
a[0]="Sudheer"
a[1]="Sunil"
a[2]="Balu"
var b=new Array(3);
b[0]="latha"
b[1]="Saraswathi"
b[2]="Usha"
for(i=0;i<a.length;i++)
{
document.write("<p>"+a[i]+"</p>")
}
document.write("<p>"+"Concat = "+a.concat(b)+"</p>")
document.write("<p>"+"Joined = "+a.join("-------- ")+"</p>")
document.write("<p>"+"Poped = "+a.pop( )+"</p>")
document.write("<p>"+"Poped ="+a.pop( )+"</p>")
14

document.write("<p>"+"Shift ="+a.shift( )+"</p>")


document.write("<p>"+"Unshift ="+b.unshift()+"</p>")
document.write("<p>"+"Sort ="+b.sort( )+"</p>")
document.write("<p>"+"Reverse ="+b.reverse( )+"</p>")
document.write("<p>"+"Slice ="+b.slice( )+"</p>")
document.write("<p>"+"Pushed ="+a.push("Sirisha")+"</p>")
document.write("<p>"+"pushed ="+a.push("Sandhya")+"</p>")
document.write("<p>"+"pushed ="+a.push("Jeevitha")+"</p>")
document.write("<p>"+"Sort ="+a.sort( )+"</p>")
for(i=0;i<a.length;i++)
{
document.write("<p>"+a[i]+"</p>")
}
</script>
</BODY>
</HTML>

O/P: - Sudheer

Sunil

Balu

Concat = Sudheer,Sunil,Balu,latha,Saraswathi,Usha

Joined = Sudheer-------- Sunil-------- Balu

Poped = Balu

Poped =Sunil

Shift =Sudheer

Unshift =undefined

Sort =Saraswathi,Usha,latha

Reverse =latha,Usha,Saraswathi

Slice =latha,Usha,Saraswathi

Pushed =1

pushed =2

pushed =3
15

Sort =Jeevitha,Sandhya,Sirisha

Jeevitha

Sandhya

Sirisha

Date class: - The date class used to work with dates & time.
Create Date object: - var d=new Date( );
Date object methods: -
Method Description
Date( ) returns today’s date & time.
getDate( ) returns the day of the month.
getDay( ) returns the day of the week (From 0 – 6).
getMonth( ) returns the month (from 0 – 11)
getFullYear( ) returns the year as a 4 digit number.
getHours( ) returns the hour (from 0 - 23).
getMinutes( ) returns the minutes (from 0 – 59).
getSeconds( ) returns the seconds (from 0 – 59).
getMilleSeconds( ) returns the milliseconds (from 0 – 999).
getTime( ) returns the no. of milliseconds since midnight jan 1,1970.
setDate( ) sets the day of the month.
setMonth( ) set the month (0 -11)
setFullYear( ) sets the year (4 digits)
setHours( ) set the Hour (0 – 23)
setMinutes( ) set the minutes (0 - 59)
setSeconds( ) set the seconds (0 – 59)

Ex: -
<!-- to display current week day, month, date, & time based on system time-->
<html>
<head>
<title> Date class </title>
</head>
<body>
<script type="text/JavaScript">
document.write("<b>today date</b>:"+Date( )+"<br>")
// to calculate years from 1970
var minutes=1000*60
hours=minutes*60
days=hours*24
years=days*365
var d=new Date( )
var t=d.getTime( )
var y=t,years
document.write("it's been: "+y +"years since 1970/01/01!"+"<br>")
16

// to set a specific date


var d=new Date( )
d.setFullYear(2007,8,19)
document.write("set specific date:" +d+"<br>")
// an array to write a week day & not just a number
var d=new Date( )
var weekday=new Array(7)
weekday[0]="Sunday"
weekday[1]="Monday"
weekday[2]="Tuesday"
weekday[3]="Wednesday"
weekday[4]="Thursday"
weekday[5]="Friday"
weekday[6]="Saturday"
document.write("Today it is "+weekday[d.getDay( )])
</script>
</body>
</html>

O/P: -
today date:Mon Sep 10 15:22:09 2007
it's been: 1189417929609years since 1970/01/01!
set specific date:Wed Sep 19 15:22:09 UTC+0530 2007
Today it is Monday

Math class: - the math class allows you to perform common mathematical tasks.
Note: - it is not required to create object to math class before using it.
We can call methods of math class as shown below.
g.f: Math.methodName( )
Math object methods: -
Method Description
abs(x) returns the absolute value of a number
ceil(x) returns the value of a number round upwards
to the nearest integer.
floor(x) returns the value number rounded downwards
to the nearest integer.
exp(x) returns the value of exponent.
log(x) returns the natural algorithm (base E) of a no.
max(x,y) returns the number with the heights value
min(x,y) returns the number with the lowest value.
pow(x,y) returns the value of x to the power of y.
random( ) return a random number between 0 & 1
round(x) rounds a number to the nearest integer 1,2,3
sqrt(x) returns the squire root of a number.
sin(x) returns the sine of an angle.
cos(x) returns the cosine value of an angle.
tan(x) returns the tangent of an angle.
17

Ex: -
<html>
<head>
<title> Math class </title>
<body>
<script language="JavaScript">
x=4.6;
y=9;
document.write("<b>absolute="+Math.abs(x)+"<br>")
document.write("<b>ceil="+Math.ceil(x)+"<br>");
document.write("<b>floor="+Math.floor(x)+"<br>");
document.write("<b>exponent="+Math.exp(x)+"<br>");
document.write("<b>logarithm="+Math.log(x)+"<br>");
document.write("<b>maximum="+Math.max(x,y)+"<br>");
document.write("<b>minimum="+Math.min(x,y)+"<br>");
document.write("<b>power="+Math.pow(y,x)+"<br>");
document.write("<b>random="+Math.random(x)+"<br>");
document.write("<b>round="+Math.round(x)+"<br>");
document.write("<b>squire="+Math.sqrt(x)+"<br>");
document.write("<b>sin="+Math.sin(x)+"<br>");
document.write("<b>cos="+Math.cos(x)+"<br>");
document.write("<b>tan="+Math.tan(x)+"<br>");
</script>
</body>
</html>

O/P: -
absolute=4.6
ceil=5
floor=4
exponent=99.48431564193377
logarithm=1.5260563034950491
maximum=9
minimum=4.6
power=24519.72208445221
random=0.468801127809111
round=5
squire=2.1447610589527217
sin=-0.9936910036334644
cos=-0.11215252693505487
tan=8.860174895648045

JavaScript functions: - in java script functions are created with the keyword
‘function’ as shown below
Syntax: - function funname( )
{
--------
18

}
Generally we can place script containing function head section of web page. There
are 2 ways to call the function.
1) direct call function
2) Events handlers to call the function dynamically.

1 We can pass data to function as argument but that data will be available inside
the function.

Ex: -
<HTML>
<HEAD>
<TITLE> Function direct call</TITLE>
<script language="JavaScript">
function add(x,y)
{
z=x+y
return z
}
</script>
</HEAD>
<BODY>
<script>
var r=add(30,60)
document.write("addition is :"+r);
</script>
</BODY>
</HTML>

O/P: - addition is :90

2 to add dynamical effects, java script provide a list of events that call function
dynamically. Hare each event is one attribute that always specified in html tags.
attrname=”attrval”
eventName=”funname( )”
Ex: -
<HTML>
<HEAD>
<TITLE> Function dynamically</TITLE>
<script language="JavaScript">
function add( )
{
x=20
y=30
z=x+y
document.write("addition is :"+z);
}
19

</script>
</HEAD>
<BODY> to call function:
<input type="button" value="click hare" onclick="add( )">
</script>
</BODY>
</HTML>

O/P: - to call function:


addition is :90

Events are not case sensitive.

Java script events: -


Attribute The event occurs when…
onclick mouse click an object
ondblclick mouse double clicks
onmouseover a mouse cursor on touch here
onmousedown a mouse button is pressed
onmousemove the mouse is moved
onmouseout the mouse is moved out an element
onmouseup a mouse button is released
onkeydown a keyboard key is pressed
onkeypress a keyboard key is pressed or held down
onkeyup a keyboard key is released
onfocus an elements get focus
onblur an element loses focus
onchange the content of a field change
onselect text is selected
onload a page or an image is finished loading
onunload the user exist the page
onerror an error occurs when loading a document or an image
onabort loading an image is interrupted
onresize a window or frame is resized
onreset the reset button is pressed
onsubmit the submit button is clicked

Ex: -
<HTML>
<HEAD>
<TITLE> Mouse Events </TITLE>
<script language="JavaScript">
function add()
{
a=55
b=45
20

c=a+b
document.write("addition is :"+c)
}
</script>
</HEAD>
<BODY>
<b onclick="add( )">
to call function click here :
</b>
<br>
<b onmouseover="add( )">
to call function touch here :
</b>
<br>
<b ondblclick="add( )">
to call function double click here :
</b>
<br>
<b onmousemove="add( )">
to call function cursor move here :
</b>
<br>
<b onmouseup="add( )">
to call function cursor up here :
</b>
<br>
<b onmouseout="add( )">
to call function cursor out here :
</b>
</BODY>
</HTML>

O/P: -
to call function click here :
to call function touch here :
to call function double click here : addition is :100
to call function cursor move here :
to call function cursor up here :
to call function cursor out here :

Program: -
<HTML>
<HEAD>
<TITLE> display student name </TITLE>
<script language="JavaScript">
function disp( )
{
21

// access from data


var name=window.document.student.sname.value
// (or) var name=window.document.getElementById("snameid").value
//checking name
if(name=""||!isNaN(name)||!isNaN(name.charAt(0)))
window.alert("sname you entered is invalid")
else
document.write("sname you have entered is : "+name);
}
</script>
</HEAD>
<BODY>
<form name="student">
Enter Student name:
<input type="text" name="sname"id="snameid" value="enter" onblur="disp( )">
</form>
</BODY>
</HTML>

O/P: -
Enter Student name:

Enter Student name:


sname you have entered is : true

Popup boxes: - popup (arises) box is a small window that always shown before
opening the page. The purpose of popup box is to write message, accept some thing
from user. Java script provides 3 types of popup boxes. They are 1) alert 2)
Confirm. 3) Prompt.

1) alert popup box :-


Alert box is a very frequently useful to send or write cautionary messages to end
use alert box is created by alert method of window object as shown below.
Syntax: - window – alert (“message”);
When alert popup, the user has to click ok before continue browsing.
Ex: -
<html>
<head>
<title> alert box </title>
22

<script language="JavaScript">
function add( )
{
a=20
b=40
c=a+b
window.alert("This is for addition of 2 no's")
document.write("Result is: "+c)
}
</script>
</head>
<body onload="add( )">
</body>
</html>

O/P: -

Result is: 60

2) confirm popup box:-


This is useful to verify or accept some thing from user. It is created by confirm
method of window object as shown below.
Syntax:-
window.confirm (“message?”);
When the confirm box pop’s up, user must click either ok or cancel buttons to
proceed. If user clicks ok button it returns the boolean valve true. If user clicks
cancel button, it returns the boolean value false.
Ex: -
<HTML>
<HEAD>
<TITLE> Confirm </TITLE>
<script>
function sub( )
{
a=50
b=45
c=a-b
x=window.confirm("Do you want to see subtraction of numbers")
if(x==true)
{
document.write("result is :"+c)
23

}
else
{
document.write("you clicked cancel button")
}
}
</script>
</HEAD>
<BODY onload="sub( )">
to see the o/p in pop up box:
</BODY>
</HTML>

O/P: -
to see the o/p in pop up box:

result is :5

3) Prompt popup box:- It is useful to accept data from keyboard at runtime. Prompt
box is created by prompt method of window object.
window.prompt (“message”, “default text”);
When prompt dialog box arises user will have to click either ok button or cancel
button after entering input data to proceed. If user click ok button it will return
input value. If user click cancel button the value “null” will be returned.
Ex: -
<HTML>
<HEAD>
<TITLE> Prompt </TITLE>
<script>
function fact( )
{
var b=window.prompt("enter +ve integer :","enter here")
var c=parseInt(b)
a=1
for(i=c;i>=1;i--)
{
a=a*i
}
window.alert("factorial value :"+a)
}
</script>
24

</HEAD>
<BODY onload="fact( )">
</BODY>
</HTML>
O/P: -

Document object model:-


“The W3C document object model (DOM) is a platform and language
neutral allows interface that programs & scripts to dynamically structure and
style of document”.
The W3C DOM provides a standard set of object for representing HTML and
XML documents and a standard interfaces for accessing and manipulating them.
The following is the hierarchy of the DOM.
|- Document --------------|- images
| Links
|- History anchors
| Objects
|- Location Embeds
| Forms
Window ----------- |
|
|- Navigator text fields
| pass words
|- Event fields
| hidden fields
|- Frames Radio button
Select
Submit
Reset
Button
Text area
File upload
Checkbox
25

navigator. app name ( )


navigator. app version ( ).

Document object properties:-


Document object is object that always refers current document body with this
object you can access existing documents and update content (text, image, list,
table, forms) of them.
g.f:- document. property name.
Property description
bgcolor sets return the background color of the document
fgcolor sets or return the text color
lastModified returns the date & time the document was last
modified
linkColor sets or returns the color of the links in the document
alinkColor sets or return the color of active links
title returns the title
URL returns the URL of the current document
vlinkColor sets or return the color of the visited links

Document object methods: -


g.f : document.methodname( )

Method Description
clear( ) clear all the elements in the document
createAttribute(“name”) create an attribute with a specified a name
createElement(“tag”) creates an element
createTextNode(“txt”) create a text string
focus( ) gives the document focus
getElementById( ) returns a reference to the first object with the
specified ID
getElementByName( ) returns a collection of objects with the
specified name
getElementByTag Name(“tag”) returns a collection of objects with the specified
TAGNAME
open( ) opens a document for writing
close( ) close the output stream & displays the sent data
write( ) write a text string to a document

Ex1: -
<HTML>
<HEAD>
<TITLE> document </TITLE>
<script>
function title1( )
{
window.alert("Title of the document is :"+document.title);
}
26

function address( )
{
window.alert("URL of the document is :"+document.URL);
}
function bgcolor( )
{
document.bgColor="yellow";
}
function mdate( )
{
window.alert("The last modified date is :"+document.lastModified);
}
</script>
</HEAD>
<BODY>
<input type="button" value="page title" onclick="title1( )"><br>
<b onmouseover="address( )">to get page address just touch this text
</b><br>
<input type="button"value="change bgcolor" onclick="bgcolor( )"> <br>
<input type="button" value="Last modified date" onclick="mdate( )">
</BODY>
</HTML>

O/P: -

Ex2: -
<HTML>
<HEAD>
<TITLE> see tag </TITLE>
<script>
function getElement( )
{
var x=document.getElementById("marqueeid");
window.alert("i am a "+x.tagName+"element")
27

}
</script>
</HEAD>
<BODY>
<marquee id="marqueeid"onclick="getElement( )">
<b><b>
Click to see what element I am i
</marquee>
</BODY>
</HTML>

O/P: -
Click to see what element I am i

Ex3: -
<HTML>
<HEAD>
<TITLE> This is main page </TITLE>
<script>
function createNewDoc( )
{
var newDoc=document.open( )
var txt="<html><head><title>This is new document </title> </head><body>
Creating about DOM is fun! </body> </html>";
newDoc.write(txt)
newDoc.close();
}
</script>
</HEAD>
<BODY onclick="createNewDoc( )">
<b>
To see the next page click here
</b>
</BODY>
</HTML>

O/P: -
28

DOM window object: -


Window object: - the window object represents the current browser window. A
window object is created automatically with every instance of a <body> or <frame>
tag.
Window object properties: -
Property description
defaultStatus sets or return the default text in the status bar of the
window.
dialogArguments returns all variables passed into the model dialog
window.
dialogHeight sets or return the height of the modal dialog window.
dialogLeft sets or return the left co-ordinates of the modal dialog
window.
dialogTop set or return the top co-ordinates of the modal dialog
window.
dialogWidth sets or return the width co-ordinates of the modal
dialog window.
length sets or return the number of frames in the window.
name sets or return the name of the window.
opener sets or return a reference to the window that created
the window.
parent returns the parent window.
returnValue sets or return the value returned from the modal
dialog window.
self returns a reference to the current window.
status sets or return the text in the status bar of the window.
top returns the topmost ancestor window.

Window object methods: -


Method description
alert( ) display an alert box with a specified message & an ok
button.

blur( ) removes focus from the current window.


close( ) closes the current window.
29

confirm( ) displays a dialog box with a specified message & ok &a cancel button.
createPop( ) create a pop-up window.
focus( ) sets focus on the current window.
moveBy(x,y) moves the window a specified number of pixels in
relation to its current co-ordinates.
navigate(“URL”) loads the specified URL into the window.
open( ) open a new browser window.
print( ) print the content of the current window.
prompt( ) displays a dialog box that prompts the user for input.
resizeBy(x,y) resizes the window by the specified pixels.
scrollBy( ) scrolls the content by the specified no. of pixels.
setInterval calls a function / evaluate an expression every time a
(function, specified interval. The arguments can take the
milliseconds) following values. Function required. A pointer to a
function or the code to be executed millisec required.
clearInterval(ID) cancels a timeout that is set with the set interval ( )
method.
setTimeout( calls a function or evaluates an expression after a
funname,millisec). specified number of milliseconds.
clearTimeout(ID) cancels a timeout that is set with the setTimeout( ) method.

Ex: -
<HTML>
<HEAD>
<TITLE> Time display</TITLE>
<script>
function startTime( )
{
var today=new Date( )
var h=today.getHours( )
var m=today.getMinutes( )
var s=today.getSeconds( )
// add a 0 in front of no's <10
m=cheakTime(m)
s=cheakTime(s)
document.getElementById("bid").innerHTML=h+":"+m+":"+s
t=window.setTimeout('startTime( )',500)
}
function cheakTime(i)
{
if(i<10)
{
i="0"+i
}
return i
}
</script>
30

</HEAD>
<BODY onload="startTime( )">
<b id="bid"> </b>
</BODY>
</HTML>

O/P: - 17:05:17

Client side validations: -


<HTML>
<HEAD>
<TITLE> client side validation </TITLE>
<script>
// validating emp name
function cheakname( )
{
var name=window.document.getElementById("enameid").value
if(name=""||!isNaN(name)||!isNaN(name.charAt(0)))
{
window.alert("name enterd is invalid")
window.document.getElementById("enameid").focus( )
window.document.getElementById("enameid").value=""
}
else
{
window.document.getElementById("noid").disabled=false;
}
}
// validating eno
function cheakno( )
{
var no=window.document.getElementById("noid").value
var no=parseInt(no)
if(no=""||isNaN(no))
{
window.alert("numbered enter is invalid")
window.document.getElementById("noid").focus( )
window.document.getElementById("noid").value=""
}
else
{
window.document.getElementById("submitid").disabled=false;
window.document.getElementById("resetid").disabled=true;
}
}
</script>
</HEAD>
31

<BODY>
<form name="emp" action=""method="get">
enter emp name:<input type="text" name="ename" id="enameid" onblur=
"cheakname( )">
<br>
enter emp id:<input type="text" name="no" id="noid" onblur="cheakno( )
"disabled><br>
<input type="submit" id="submitid" value="send" disabled>
<input type="reset" id="resetid" value="clear">
</form>
</BODY>
</HTML>

O/P: -
enter emp name: :
enter emp id:
send clear

enter emp name: :


enter emp id:
send clear

Das könnte Ihnen auch gefallen