0% found this document useful (0 votes)
2 views43 pages

2-JavaScript(1)

Chapter 2 of the document provides an overview of JavaScript programming, detailing key concepts such as objects, properties, methods, and events. It also discusses variables, their naming conventions, data types, and conversion functions, along with user interaction methods like alert, confirm, and prompt. Additionally, it introduces operators and expressions, including arithmetic, comparison, string, and logical operators, along with examples to illustrate their usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views43 pages

2-JavaScript(1)

Chapter 2 of the document provides an overview of JavaScript programming, detailing key concepts such as objects, properties, methods, and events. It also discusses variables, their naming conventions, data types, and conversion functions, along with user interaction methods like alert, confirm, and prompt. Additionally, it introduces operators and expressions, including arithmetic, comparison, string, and logical operators, along with examples to illustrate their usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Java Script

Chapter – 2: Overview of Programming in Java Script

1. Object, containership and properties

• Six entities in Java Script programmes:

1. Objects - Strictly designed elements of the browser and the HTML


documents displayed by the browser.

2. Properties - Attributes of an object, such as colour

3. Methods - Unique tasks that can be performed on certain Java Script objects

4. Functions - Special purpose (user defined) methods that can be applied


irrespective of most objects
5. Statements - Programming instructions that tell the browser how to proceed
further.
6. Events - Actions evoked by the user that can trigger a response from the
browser

• Containership (‘chimney in house’ example; chimney is a property of house)

• Partial hierarchy of objects in Java Script

The Browser

Math * Date * Window * String *

Document

Link Form Anchor

Select Button/ Text/ Radio Check box


Submit/ Textarea
Reset

* Top level objects


• Example programme to highlight hierarchy of objects in Java Script

<HTML>
<HEAD>
<script>

</script>
<TITLE>
Program to highlight hierarchy of objects
</TITLE>
</HEAD>
<BODY>
<FORM NAME="frm">
<INPUT TYPE="text" NAME="txt1">
</FORM>
<SCRIPT>
document.frm.txt1.value = "abc"
</SCRIPT>
</BODY>
</HTML>
• Properties – two types

1. Themselves objects of some parent object.


2. Single ended – containing specific values

2. Some important points about Java Script programming

• Hiding Java Script from non – java Script browsers


<SCRIPT>
<! - -
document.write(“Hello”)
// - - >
</SCRIPT>

• Providing alternative text for non-java Script browser

<SCRIPT>
<! - -
document.write(“Hello”)
// - - >
</SCRIPT>
<NONSCRIPT>
[Java Script]
</NONSCRIPT>

(</NONSCRIPT> is actually a tag for Java Script enabled browsers)

• Java Script comments (effective only within <SCRIPT>tags)


// This comment continues till end of line
/*
This is a
multi line
comment
*/

• Generating HTML

<HTML>
<HEAD>
<TITLE>
Generating HTML code from Java Script
</TITLE>
<SCRIPT>
document.write("<FONT COLOR='red'>Hello</FONT>")
</SCRIPT>
</HEAD >
</HTML>
generateHTML.html

• Notice the importance of document.write( ) – can be used for writing much


more complex HTML code which in turn can be based on certain conditions.

• Notice the nesting rule for quotes – double quotes within single quotes and vice-versa.

3. Variables and their uses

• Variables
Used to store values
Memory space
Value contained in the variable can vary

• Variable names
Begin with A – Z, a – z, _ , $
Remaining characters can be A – Z, a – z, _ , $, 0 – 9
Case sensitive
$ sign used for machine generated code and should be avoided.

• Specifying data type unnecessary and not allowed


(Type of a variable implicitly defined based on the literal values assigned to it)

• Four primitive types of values to which variables can be equated and declared
1. Number integer float (e.g. x = 2, y = 3.1, z = -0.9142 etc.)
2. Boolean – true or false (e.g. flag = false, status = true etc.)
3. Strings – characters enclosed in single / double quotes (e.g. name =
‘Ajay’.str – ‘abc’, num – ‘9940037’ etc.
4. Null – nul (e.g. p – null)

• Complex types like object types

(e.g. Date is an object type;


now = new Date ( );
note the use of new operator which is not necessary in variables of
fundamental date types;)
4. Conversion functions

1. The eval ( ) Function


• to convert string expression to a numeric value
• e.g. total = eval (“432.1*10”) {total 4321}
• if string passed does not represent a numeric value, then error

2. The parseInt ( ) Function


• to convert string value to a numeric value
• e.g.
(i) total = parseInt(“123”) {total = 123}
(ii) total = parseInt(“123xyz”) {total = 123}
(iii) total = parseInt(“xyz”) {total = 0}

3. The parseFloat ( ) Function


• to convert string value to a floating type numeric value
• e.g.
(i) x = perseFloat(“2.le4”) {x = 21000}
(ii) x = perseFloat(“2.le4xyz”) {x = 21000}
(iii) x = perseFloat(“xyz”) {x = 0}

4. The prompt ( ) Function


• Method of window object

• Displays message box with


(i) The text passed as the first parameter to the function call
(ii) A text box with default text passed as the second parameter to the
function call
(iii) An OK button
(iv) A Cancel button

• Takes to parameters
(i) String to be display as static text on the message box
(ii) String to be displayed as default text in the text box (if this parameter
is omitted, then the default text is undefined).

• Returns null if the use clicks on Cancel; returns the string entered in the text
box if the use clicks on OK

• Example programme to illustrate the use of the prompt ( ) function


<HTML>
<BODY>
<SCRIPT>
str = prompt("Hello", "Type something!!")
document.write(str)
</SCRIPT>
</BODY>
prompt.html
• Some important functions for communicating with the user

1. The alert ( ) function


• Method of window object
• Displays a message box with the following contents
➢ The text passed as a parameter to the function call
➢ An OK button
• Takes only one parameter which should be the string to be displayed as static
text on the message box.
• Does not return a value
• Example to illustrate the use the alert ( ) function
<SCRIPT>
alert("Hellow World!!")
x=3
alert ("x = "+x)
</SCRIPT>
alert.html

2. The confirm ( ) function


• Similar to alert ( ) function
• Method of window object
• Displays a message box with the following contents
➢ The text passed as a parameter to be function call.
➢ An OK button
➢ A Cancel button
• Takes only one parameter which should be the string to be displayed as static
text on the message box.
• Returns true if the user clicks OK; returns false if the user clicks Cancel
• Example to illustrate the use the alert ( ) function
<SCRIPT>
r = confirm ("Are you sure?")
document.write("Return value = "+ r + '<BR>')
</SCRIPT>
confirm.html
Java Script
Chapter – 3 : Operators, Constructs and Functions

1. Operators and Expressions


1.1 Introduction
➢ operator = pre-defined symbol for carrying out pre-specified computation on
values (known as operands) that are passed to it; used to transform one or more
values into a single resultant value.
➢ expression = group of properly arranged operators and operands that returns a
value.
➢ types of operators based upon the number of operands passed to them
o Unary operators : take only one operand.
o Binary operators : take two operands
o Ternary operators : take three operands
➢ types of operators based upon the type of computation they carry out
o Arithmetic operators
o Comparison (Relational) operators
o Logical operators
o String operators
o Assignment and arithmetic assignment operators
o Conditional operator
➢ x*y is same as y*x but “ab” + “cd” is not the same as “cd” + “ab”
1.2 The types of operators based upon the type of computation they carry out
1.2.1 Arithmetic operators

Operator Description
+ Addition
- Subtraction or unary negation
* Multiplication
/ Division
% Modules
++ Increment and then return a value (prefix notation) OR return
value and then increment (postfix notation)
-- Decrement and then return a value (prefix notation) OR return
value and then decrement (postfix notation)
➢ Example to illustrate the use of arithmetic operators
<SCRIPT>
x=5
y=3
document.write(“x=”+x+“.y=”+y+‘<BR>’)
document.write(“x+y=“+(x+y)+‘<BR>’)
document.write(“x-y=“+(x-y)+‘<BR>’)
document.write(“x*y=“+(x*y)+‘<BR>’)
document.write(“x/y=“+(x/y)+‘<BR>’)
document.write(“x%y=“+(x%y)+‘<BR>’)
document.write(“x=”+x++‘<BR>’)
document.write(“After y=x++”+‘<BR>’)
y=x++
document.write(“x=”+x+“, y=”+y+‘<BR>’)
document.write(“After y=++x”+‘<BR>’)
y=--x
document.write(“x=”+x+“,y=”+y+‘<BR>’)
document.write(“After y=--x”+‘<BR>’)
y=--x
document.write(“x=”+x+“,y=”+y+‘<BR>’)
</SCRIPT>
arithOp.html

1.2.2 Comparison (Relational) operators


➢ used to compare values
➢ expressions having relational operators return either true or false and are
known as test expressions.

Operator Description
== Equal
=== Strictly equal
!= Not equal
!== Strictly not equal
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
➢ “5”==5 is true (automatic type conversion); “5”===5 is false (no automatic
type conversion)
➢ “5”!=5 is false (automatic type conversion); “5”!==5 is true (no automatic
type conversion)
1.2.3 String Operators
➢ currently only the operator (string concatenation) operator, used to join
two strings, e.g. “ab”+“cd” produces “abcd” (but “cd”+“ab” produces
“cdab”)
➢ values of different types can also be concatenated by the + operator
(automatic type conversion to string occurs)
➢ example programme to illustrate the use of + operator
<SCRIPT>
document.write(' "ab"+"cd" = '+"ab" + "cd" + '<BR>')
document.write(' "cd"+"ab" = '+"cd" + "ab" + '<BR>')
x=3
p = "x = " + x
document.write(p+'<BR>')
</SCRIPT>
stringOp.html

1.2.4 Assignment and arithmetic assignment operator

Operator Description
= Sets the variable on the left of the = operator to the value of
the expression on its right
+= Increments the variable on the left of the += operator by the
value of the expression on its right. When used with strings,
the value to the right of the += operator is appended to the
value of the variable on the left of the += operator.
-= Decrements the variable on the left of the -= operator by the
value of the expression its right.
*= Multiplies the variable on the left of the *= operator by the
value of the expression on its right.
/= Divides the variable on the left of the /= operator by the value
of the expression on its right.
%= Takes the modules of the variable on the left of the %=
operator by the value of the expression on its right.

➢ Example programme to illustrate the use of relational operators


<SCRIPT>
document.write('"5" ==5 is '+("5"==5)+'<BR>')
document.write(' "5" ===5 is '+("5"===5)+'<BR>')
document.write(' "5" !=5 is '+("5"!=5)+'<BR>')
document.write(' "5" !==5 is '+("5"!==5)+'<BR>')
document.write('6>5 is '+(6>5)+'<BR>')
document.write('5>5 is '+(5>5)+'<BR>')
document.write('5>=5 is '+(5>=5)+'<BR>')
document.write('5<6 is '+(5<6)+'<BR>')
document.write('5<5 is '+(5<5)+'<BR>')
document.write('5<=5 is '+(5<=5)+'<BR>')
document.write('5!=5 is '+(5!=5)+'<BR>')
document.write('5!=6 is '+(5!=6)+'<BR>')
</SCRIPT>
relaOp.html

1.2.5 Logical Operators


➢ Used to combine two or more test expressions

Operator Description
&& Logical AND
II Logical OR
! Logical NOT

➢ example to illustrate use of logical operators


<SCRIPT>
document.write("false && false is "+(false && false) +'<BR>')
document.write("false && true is "+(false && true) +'<BR>')
document.write("true && false is "+(true && false) +'<BR>')
document.write("true && true is "+(true && true) +'<BR>')
document.write("false || false is "+(false || false) +'<BR>')
document.write("false || true is "+(false || true) +'<BR>')
document.write("true || false is "+(true || false) +'<BR>')
document.write("true || true is "+(true || true) +'<BR>')
document.write("!true is "+(!true) +'<BR>')
document.write("!false is "+(!false) +'<BR>')
</SCRIPT>
logicOp.html
➢ Example to illustrate use of arithmetic assignment operators
<SCRIPT>
str="abc"
document.write(" Now str= "+ str+'<BR>')
document.write("Statement executed:str+='def'"+'<BR>')
str+='def'
document.write(" Now str= "+ str+'<BR>')
document.write("Statement executed : x=3" + '<BR>')
x=3
document.write("Now x="+x+ '<BR>')
document.write("Statement executed : x+=11" + '<BR>')
x+=11
document.write("Now x="+x+'<BR>')
document.write("Statement executed : x-=2" + '<BR>')
x-=2
document.write("Now x="+x+'<BR>')
document.write("Statement executed : x*=2" + '<BR>')
x*=2
document.write("Now x="+x+'<BR>')
document.write("Statement executed : x/=4" + '<BR>')
x/=4
document.write("Now x="+x+'<BR>')
document.write("Statement executed : x%=5" + '<BR>')
x%=5
document.write("Now x="+x+'<BR>')
</SCRIPT>
assignOp.html
1.2.6 The conditional ternary operator

➢ Symbol - ?:
➢ Three operands
1. Test expression
2. Value to be returned if condition is true
3. Value to be returned if condition is false
➢ Syntax
Var + condition ? value1 : value 2
➢ Example programme to illustrate the use of conditional operator
<SCRIPT>
document.write("(3>4) ? 1:0 = " + ( (3>4) ? 1 : 0) + '<BR>')
</SCRIPT>
ternaryOp.html

2. Java Script Programming Statements

2.1 Introduction
• Programming constructs in Java Script are of the following types
A. Decision making constructs
1. The if .. else construct
2. The switch .. case construct

B. Looping constructs
1. The while loop
2. The do .. while loop
3. The for loop
• Semi-colons should separate multiple statements on the same line of text
• Non semi-colons required if statements are on separate lines
• No line-continuation identifiers required in a statement while spans several lines
of text.

2.2 The programming constructs


2.2.1 The if..else construct
• Enables us to apply a condition on the execution of statements
• General syntax (without else)
If(test_expr)
{
Set of statements
}
test_expr is a test expression which returns either true or false; statements
within curly braces executed only if test_expr returns true.
• General syntax (with else)
If(test_expr)
{
first set of statements
}
else
{
second set of statements
}
if test_expr is true, then only first set of statements executed; otherwise
only second set of statements executed.
• example programmes to illustrate the use of switch..case construct
<SCRIPT>
x=3
switch(x)
{
case 1:
alert("one")
break
case 2:
alert("two")
break
case 3:
alert("three")
break
case 4:
alert("four")
break
default:
alert("Out of range")
}
</SCRIPT>
switch_case1.html
Example programme to illustrate the use of if..else
<SCRIPT>
str = prompt("enter a number")
x = parseInt(str)
if(x%2==0)
{
alert("The number is even")
}
else
{
alert("The number is odd")
}
</SCRIPT>
if_else.html
2.2.2 The switch..case construct
❖ Used to take multi-way decisions
❖ General syntax
switch (variable)
{
case value1:
statements
break
case value 2:
statements
break
…. …. …. ….
…. …. …. ….
case value n :
statements
break
default :
statements
}
• value, value2, … valuen know as case constants
• value of variable tested against each and every case constant
• if match found statements following the case constants executed
• if no match found then statements following default executed
• break (optional) after every set of statements to ensure that the control
comes out of switch case and statements following the next case
constant are not executed.
❖ The break statements : forces an unconditional termination of the loop
❖ Example to illustrate the use of the break keyword
<SCRIPT>
ans = prompt('Do you want to find inverse of numbers ? (y/n)','y')
while(ans=='y' || ans =='Y')
{
x = prompt ( 'enter the number')
y = parseFloat(x)
if (y==0)
{
alert("Invalid entry")
break
}
alert("Inverse of" +y+ "is" + 1/y)
ans=prompt('Enter another?(y/n)', 'y')
}
</SCRIPT>
break.html
❖ The continue keyword : forces an unconditional repetition of the loop
❖ Example to illustrate the use of the continue keyword
<SCRIPT>
ans = prompt('Do you want to find inverse of numbers ? (y/n)', 'y')
while(ans=='y' || ans =='Y')
{
x = prompt ( 'enter the number', '0')
y = parseFloat(x)
if (y==0)
{
alert("Invalid entry ... Try again")
continue
}
alert("Inverse of" +y+ "is" + 1/y)
ans=prompt('Enter another?(y/n)', 'y')
}
</SCRIPT>
continue.html
2.2.3 The while loop
❖ used to repeat the execution of a set of statement while a certain condition is true.
❖ normally used when the number of iterations is not known in advance; iteration
stops when the condition become false as a result of an event whose exact time of
occurrence is not possible to predict (e.g. the user’s to terminate the loop after an
unpredictable number iterations)
❖ syntax
while (condition)
{
statements
}
• first of all, condition is tested
• if the condition is true, statements executed and condition tested again
• if condition becomes false, control is transferred out of the loop
❖ examples to illustrate the use of the while loop
<SCRIPT>
ans = prompt('Do you want to find squares of numbers ? (y/n)', 'y')
while (ans =='y' || ans == 'Y')
{
x = prompt( 'enter the number', '0')
y = parseFloat(x)
alert ("Square of " +y+ " is " + y*y)
ans=prompt('Enter another ? (y/n)', 'y')
}
</SCRIPT>
while.html

2.2.4 The do..while loop


❖ Works in exactly the same way as while loop except that the test expression is
tested at the end of the loop (hence at least one iteration of the loop is guaranteed)
❖ Example to illustrate the use of the do .. while loop
<SCRIPT>
do
{
x = prompt( 'enter the number', '0')
y = parseFloat(x)
alert ("Square of " +y+ " is " + y*y)
ans = prompt('Enter another ? (y/n)', 'y')
} while(ans=='Y'|| ans=='y')
</SCRIPT>
2.2.5 The for loop
❖ Also used to repeat the execution of a set of commands
❖ Normally used when the number iterations is known is advance
❖ Syntax
for(init_expr = initialization expression
{
Statements
}
❖ init_expr = initialization expression
❖ test_expr = test expression
❖ re_init_expr = re-initialization expression
1. variables are initialized in the test_expr.
2. the test_expr is tested; if true, then go to setp 3, else exit the loop
3. execute the statements
4. execute the re-init_expr in which the variables are re-initialized
5. go to step 2
❖ examples to illustrate the use of the for loop
<SCRIPT>
for (i=0, i<10, i++)
document.write(i+‘<BR>’)
</SCRIPT>
for.html
<SCRIPT>
colorArray=new Array('red', 'blue', 'green', 'yellow', 'black', 'brown')
for (i=0; i<6; i++)
{
y1= '<FONT COLOR="' + colorArray[i] + '">'
document.write(y1)
document.write("<h2>Hello</h2><BR>")
document.write('</FONT>')
}
</SCRIPT>
forColor.html
3. Functions
3.1 Introduction
❖ Function = block of statements referenced and executed as a single unit
❖ Parameters = data required for execution of the function
❖ Function may or may not return a value
❖ Invocation of function that returns a value is usually part of a statement
e.g.
n = factorial (5)
❖ Invocation of function that does not return a value is a complete statement
e.g.
error(‘Invalid entry’)

3.2 Defining a function


❖ Function must be defined before it can be used
❖ Definitions usually placed in the head section of the HTML files
❖ Syntax
function functionName(p1, p2, ….., pn)
{
statements
}
❖ functionName = name of the function
❖ p1, p2, …., pn = names of parameters
3.3 Local variable declarations
❖ Variables declared even within a function definition are global by default.
❖ Resulting problem illustrated by the following diagram.

1 2

A script is the script invokes


executed that function execute A ( )
assigns 10 to X
function executeA( )
X = 10 {
executeA() executeB()
document.write(X) }

3
5

The script malfunctions as a function execute () invokes


result of X being inadvertently function execute()
changed by function
execute ()

function execute() sets X function executeB( )


to 0, unaware of the fact {
that it was indirectly called X=0
by a script that also uses }
the variable X

❖ Therefore variables should be declared as local variables so that any change in them
does not reflect in the values of global variables or variables of other functions.

❖ Use the var keyword to declare local variables as follows


var temp
var index = 1
var product = new Array (10)

3.4 The return statement

❖ Function can return a value to the statement that invoked the function.
❖ Syntax
Return expression
❖ expression should evaluate to a value
❖ Function terminates with the return statement.
❖ An example programme to illustrate the use of the return statement
<HTML>
<HEAD>
<TITLE>
The return statement
</TITLE>
<SCRIPT>
function square(a)
{
var p = a*a
return p
}
document.write("Square of 5 is " + square(5)+'<BR>')
</SCRIPT>
</HEAD>
</HTML>
return.html

❖ An example programme to illustrate the use of the arguments array


<HTML>
<HEAD>
<TITLE>
Functions with variable number of parameters
</TITLE>
<SCRIPT>
function display()
{
x = display.arguments.length
for(i=0; i<x; i++)
document.write(arguments[i]+ '<BR>')
}
display("Hello", "and", "Welcome to JavaScript")
display("This is a function with", "variable number of
parameters")
</SCRIPT>
</HEAD>
</HTML>
varParam.html

❖ e.g.
<HTML>
<HEAD>
<TITLE>
Defining and using functions
</TITLE>
<SCRIPT>
//function definition
function display(text)
{
document.write(text)
}
//function call
display("xyz")
</SCRIPT>
</HEAD>
</HTML>
function.html

❖ Implicitly an equation is set up


text = “xyz”
text automatically becomes object of the type String

3.5 Function with variable number of parameters

❖ An array called arguments array automatically gets created by Java Script for
each function invocation.
❖ Suppose function f is called as follows
F (“test”, true, 77)
then
f.arguments.length = 3
f.arguments[0] = “test”
f.arguments[1] = true
f.arguments[2] = 77
Java Script
Chapter – 4 : Handling Events

❖ Event : user’s action on the web page


❖ Event handling : responding to the event
❖ Event handlers : code that executes the response

❖ Things that can be done by Java Script event handlers (partial list)
➢ Display a dialog box when the user moves the mouse over the link
➢ Validate the date the user has just entered into a form
➢ Load and display an animation sequence when a user clicks a button
➢ Interact with java applets and browser plug-ins.

❖ Event handling is two – step process:


➢ Defining the events that can be handled by scripts
➢ Providing a standard method of connecting these events to user-supplied Java
Script code.

❖ Event symbolized by attribute of the object on which the event occurs.


❖ Attribute equated to a call to the function (in double quotes) which is specified as the
event handler

❖ Table of event handling attributes.

EVENT HANDLING IDENTIFIES CODE TO EXECUTE UNDER THESE


ATTRIBUTES CIRCUMSTANCES

OnAbort The loading of an image aborted as a result of user’s actions.


A document, windows, frame set or form element loses the current
OnBlur
input focus.
A text field, text area, file upload field or selection is modified and
OnChange
loses the current inputs focus.

OnClick A link**, client side image map area or form element is clicked.
A link **, client side image map area or document is double
OnDblClick*
clicked.
OnError An error occurs during the loading of an image, frame or window
A document, windows, frame set or form element receives the
OnFocus
current input focus.

* will work only if onClick event is not thee


** will work only if HREF = “javascript:void (0)”
EVENT HANDLING IDENTIFIES CODE TO EXECUTE UNDER THESE
ATTRIBUTES CIRCUMSTANCES
OnKeyDown The user presses a key
OnKeyPress The user presses and releases a key
OnKeyUp The user releases a key
OnLoad An image, document of frameset is loaded
OnMouseDown The user presses a mouse button
OnMouseMove The user moves the mouse
OnMouseOut The mouse is moved out of a link or an area of client – side image map
OnMouseOver The mouse is moved over a link or an area of a client – side image map.
OnMouseUp The user releases a mouse button
OnMove The user moves a window or a frame
OnReset The user clicks on the forms reset button
OnResize The user resizes a window or a frame
OnSelect Text is selected in a text field or text area
OnSubmit A form is submitted
OnUnload The user exits a document or frame set

<HTML>
<HEAD>
<SCRIPT>
count = 0
function focusCount()
{
++count
alert ("You have moved your mouse here " + count + " times")
}
</SCRIPT>
</HEAD>
<BODY>
<A HREF = "javascript:void(0)" ONMOUSEOVER = 'focusCount()'>
Point here
</A>
</BODY>
</HTML>
onMouseOver1.html

<INPUT TYPE="button" VALUE="Confidential !!"


ONMOUSEOVER="window.status='Click to gain access'"
ONMOUSEOUT = "window.status=''">
OnMouseOver2.html
<INPUT TYPE="button" VALUE="Confidential !!"
ONMOUSEOVER="document.bgColor='red'"
ONMOUSEOUT="document.bgColor='green'">
OnMouseOver3.html
<HTML>
<HEAD>
<SCRIPT>
count = 0
function countChance()
{
count++
if(count>5)
{
alert("You have exhausted your chances")
window.close()
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<INPUT TYPE="button" VALUE="Restart game")
ONCLICK = "countChance()">
</FORM>
</BODY>
</HTML>
Restrict.html

<HTML>
<HEAD>
<SCRIPT>
function show()
{
document.form1.myimg.src= "a.jpg"
}
function hide()
{
document.form1.myimg.src= "javascript : void(0)"
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="form1">
<IMG SRC="b.jpg" name="myimg">
<INPUT TYPE="button" VALUE="Show image" ONCLICK="show()">
<INPUT TYPE="button" VALUE="Hide image" ONCLICK="hide()">
</FORM>
</BODY>
</HTML>
showHide.html

<HTML>
<HEAD>
<TITLE>Body onLoad and onUnload Event</TITLE>
</HEAD>
<BODY ONLOAD = "alert('Hello')" ONUNLOAD = "alert('Bye Bye !')">
</BODY>
</HTML>
Onload_unload.html

❖ onFocus to restore a document tio default settings or to continue previously interrupted


processing
❖ onBlur to stop animation / processing no longer necessary (so as to save resources)
❖ <! – frames.html ->
<HTML>
<HEAD>
<TITLE> OnFocus OnBlur</TITLE>
</HEAD>
<FRAMESET COLS = "*,*">
<FRAME SRC = "doc1.html">
<FRAME SRC = "doc2.html">
</FRAMESET>
</HTML>

<! – doc1.html ->


<HTML>
<HEAD>
<SCRIPT LANGUAGE = "javaScript">
function gotfocus()
{
document.bgColor = "#FFFFFF"
}
function lotsfocus()
{
document.bgColor = "#FF0000"
}
</SCRIPT>
</HEAD>
<BODY onFocus="gotfocus()" onBlur="lostfocus()" bgColor="#000000">
<H1>Document 1 </H1>
</BODY>
</HTML>

<! – doc2.html ->


<HTML>
<HEAD>
<SCRIPT LANGUAGE = "javaScript">
function gotfocus()
{
document.bgColor = "#FF0000"
}
function lotsfocus ()
{
document.bgColor = "#FFFFFF"
}
</SCRIPT>
</HEAD>
<BODY OnFocus="gotfocus()" OnBlur="lostfocus()" bgColor="#000000">
<H1>Document 2 </H1>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE> Image event handling </TITLE>
<SCRIPT>
function imageLoaded()
{
alert(document.image[0].src + "has been loaded")
}
function imageAborted()
{
alert("Hey! You just aborted the loading of the last image")
}
function imageError()
{
alert("Error loading image")
}
</SCRIPT>
</HEAD>
<BODY>
<IMG SRC="a1.jpg" ONLOAD="imageLoaded()" ONABORT="imageAborted()"
ONERROR="imageError()">
</BODY>
</HTML>
Onabort_onerror.html
❖ Image maps

Image
Area 1
(clicking leads
to URL1)
Area 2
(clicking leads to URL2)

Image map : map between areas in the image and specified URLs
clicking on a certain point co-ordinates passed (which region?) determined
appropriate URL returned
- server side image map = map on the server
- client side image map = map is part of web page and gets downloaded on to the clients
computer
<IMG SRC = "a.jpg" HEIGHT = 400 WIDTH = 400 USEMAP = "#MAP1">
<MAP NAME = "map1">
<AREA COORDS = "0,0,200,200" HREF = "one.html">
<AREA COORDS = "200,0,400,200" HREF = "two.html">
<AREA COORDS = "0,200,200,400" HREF = "three.html">
<AREA COORDS = "200,200,400,400" HREF = "four.html">
</MAP>
maps1.html

ONMOUSEOVER and ONMOUSEOUT event can be attached to each AREA tag

❖ Form events
Event Form Element Event – handling attributes
The form is submitted by the Overall form OnSubmit
user
The form is reset by the user Overall form OnReset
The form element loses the All form elements OnBlur
input focus
The form element receives All form elements OnFocus
the input focus
The form element is modified Select field, text field, onChange
and loses the current input text area field
focus
Text is selected Text field or text area OnSelect
A button or checkbox is Button, submit onClick
clicked button, reset button,
radio button or
checkbox
A mouse button is pressed or Button OnMouseDown, onMouseUp
released
A key is pressed, released or Text area OnKeyDown, onKeyUp,
pressed and released onKeyPress
❖ <! – Script with function to prevent embedded blanks - >
<HTML>
<HEAD>
<TITLE> Validating text</TITLE>
<SCRIPT>
function textSelect()
{
if (isBlank(document.form1.text1.value))
{
document.form1.text1.value="#ERROR!!"
document.form1.text1.focus()
document.form1.text1.select()
}
}
function isBlank(s)
{
var ret=false
var len=s.length
var i
for (i=0;i<len;i++)
{
if (s.charAt(i)==" ")
{
ret = true
break
}
}
return ret
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="form1">
<INPUT TYPE="text" NAME="text1"
onChange="textSelect()">
</FORM>
</BODY>
</HTML>
blanks.html

• Programme to process forms


<HTML>
<HEAD>
<TITLE>
Button and checkbox events
</TITLE>
<SCRIPT LANGUAGE = "javaScript">
function showResults()
{
var resultMsg = ""
if (document.survey.age[0].checked)
resultMsg += "under 30,"
if (document.survey.age[1].checked)
resultMsg += "between 30 - 60,"
if (document.survey.age[2].checked)
resultMsg += "over 60,"
if (document.survey.sex[0].checked)
resultMsg += "male,"
if (document.survey.sex[1].checked)
resultMsg += "female,"
if (document.survey.reading.checked)
resultMsg += "reading,"
if (document.survey.eating.checked)
resultMsg += "eating,"
if (document.survey.sleeping.checked)
resultMsg += "sleeping,"
document.survey.result.value=resultMsg
}
function upperCaseResults()
{
var newResults = document.survey.result.value
document.survey.result.value=newResults.toUpperCase()
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME = "survey">
<B>Age : </B>
<INPUT TYPE = "radio" NAME= "age" ONCLICK =
"showResults()">Under 30
<INPUT TYPE = "radio" NAME= "age" ONCLICK =
"showResults()">Under 30 - 60
<INPUT TYPE = "radio" NAME= "age" ONCLICK =
"showResults()">Over 60
<BR>
<BR>
<B> Sex : </B>
<INPUT TYPE = "radio" NAME = "sex" ONCLICK =
"showResults()"> Male
<INPUT TYPE = "radio" NAME = "sex" ONCLICK =
"showResults()">Female
<BR>
<BR>
<B> Interests : </B>
<INPUT TYPE = "checkbox" NAME = "reading" ONCLICK =
"showResults()"> Reading
<INPUT TYPE = "checkbox" NAME = "eating" ONCLICK =
"showResults( )">Eating
<INPUT TYPE = "checkbox" NAME = "sleeping" ONCLICK =
"showResults( )">Sleeping
<BR>
<BR>
<B>Results : </B>
<INPUT TYPE = "text" NAME = "result" SIZE = 60>
<BR>
<INPUT TYPE = "button" VALUE = "Convert to upper case"
ONCLICK = "upperCaseResults()">
<BR>
<INPUT TYPE = "Submit" VALUE = "OK" ONCLICK = "return
confirm('Sure?')">
<INPUT TYPE = "Reset" VALUE = "Clear" ONCLICK = "return
confirm('Sure?')">
</FORM>
</BODY>
</HTML>
formProcess.html
• Selection list event handling
<HTML>
<HEAD>
<TITLE> Handling selection list events </TITLE>
<SCRIPT>
function updateOrder()
{
var orderString = ""
var n = document.diner.entries.length
for (var i=0;i<n;i++)
{
if(document.diner.entries.options[i].selected)
{
orderString += document.diner.entries.options[i].value+'\n'
}
}
document.diner.summary.value += orderString
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME = "diner">
<SELECT NAME="entries" SIZE=4 MULTIPLE
ONCHANGE="updateOrder()">
<OPTION VALUE = "Sadda Dosa"> Sadda Dosa
<OPTION VALUE = "Masala Dosa"> Masala Dosa
<OPTION VALUE = "Idli"> Idli
<OPTION VALUE = "Vada"> Vada
<OPTION VALUE = "Masala Uttapam"> Masala Uttapam
<OPTION VALUE = "Onion Uttapam"> Onion Uttapam
</SELECT>
<BR>
<BR>
<B> You ordered </B>
<BR>
<TEXTAREA NAME = "summary" ROWS = 4 COLS = 20>
</TEXTAREA>
</FORM>
</BODY>
</HTML>
selectionProcess.html
• Simulating events
<HTML>
<HEAD>
<TITLE>Simulating Events</TITLE>
<SCRIPT>
function button1Clicked()
{
document.test.button2.click()
}
function button2Clicked()
{
alert("Button2 was clicked")
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME = "test">
<INPUT TYPE = "button" NAME = "button1" VALUE = "Button1"
ONCLICK = "button1Clicked()">
<INPUT TYPE = "button" NAME = "button2" VALUE = "Button2"
ONCLICK="button2Clicked()">
</FORM>
</BODY>
</HTML>
simulate.html

• The event object


o Introduced in JavaScript 1.2
o Provides additional information about events (manifested as values of its
properties)
o Properties available for event object depend upon
▪ Type of event
▪ Browser
• Internet explorer defines a global object named event that can be accessed from the event
handling function
function myEventHandler ( )
{
windows.status(event.screenX = “,”+event.screnY)
}
• Netscape Navigator does not define a global event object. Instead, it implicitly passes an
event object to event handling functions.
function myEventHandler(eventObj)
{
windows.status(eventObj.screenX + “,”+eventObj.screenY)
}
• Ensure compatibility by explicitly passing the event objet to the event handling function
call.
<HTML>
<HEAD>
<TITLE>
Using the event object
</TITLE>
<SCRIPT>
function stat(eventObj)
{
window.status = eventObj.screnX + ", " + eventObj.screenY
}
</SCRIPT>
</HEAD>
<BODY ONMOUSEMOVE = "stat(event)">
</BODY>
</HTML>
mousepos.html
Java Script
Chapter – 5 : Working with objects

1. Browser Objects

1.1 Table of browser objects

Object Use
window object To access a browser window or a frame within a window. The window
object is assumed to exist and does not require the window prefix when
referring to its properties and methods.
document object To access the document that is currently loaded into the window. A
document object refers to an HTML document that provides content, that
is, one that has HEAD and BODY tag.
location object To represent a URL. It can be used to create a URL object, access parts of
a URL, or modify an existing URL.
frame object To access an HTML frame. The frames array is used to access all the
frames array frames within a window
image object To access an image that is embedded in an HTML document. The image
images array array is used to access all image objects within a document.
form object To access an HTML form. The forms array is used to access all forms
forms array within a document.
text object To access the text field of a form
textarea object To access a text area field of a form
radio object To access a set of radio buttons of a form r to access an individual button
within the set.
checkbox object To access checkbox within a form
button object To access a form button that is not submit or reset button.
submit object To access a submit button of a form
reset object To access a reset button or a form
select object To access a select list of a form
option object The option object is used to access the elements of a select list.
password object To access a password field of a form
navigator object To access information about the browser that is executing the script.

1.2 The browser object hierarchy

1.2.1 The instance hierarchy

• browser creates objects as a result of web page design


• object arranged into a hierarchy that corresponds to the structure of the
loaded web documents and current state of browser.
• This hierarchy is known as instance hierarchy.

1.2.2 The window object

• top level object


• represents a browser window
• its properties used to identify the HTML elements that comprise the windows.
• some properties of window object.
windows

frames document location status


array

Links forms images


array array array

1.2.3 The navigator object

• top level object


• used to describe the configuration of the browser being used
• some properties are appCodename, appVersion etc.

1.3 Hierarchical object identifiers

• An example of instance hierarchy to access the name of a radio button which is


the fifth element of the second form, the identifier will be
document.forms[1].elements[4].name

• No need to identify the window object when you refer to the current window i.e.
no need to write
window.document.forms[1].elements[4].name

❖ An example to illustrate the hierarchical object identifiers


<HTML>
<HEAD>
<TITLE>Using Hierarchial Object Identifiers</TITLE>
<SCRIPT>
outputWindow = open("", "output")
function setupWindow()
{

outputWindow.document.write("<HTML><HEAD><TITLE>Output
Window</TITLE></HEAD><BODY>")
}
function describeBrowser()
{
outputWindow.document.write("<H2>Browser
properties</H2>")

outputWindow.document.write(navigator.appCodeName+'<BR>')
outputWindow.document.write(navigator.appName+'<BR>')
outputWindow.document.write(navigator.appVersion+'<BR>')
}
function describeWindow()
{
outputWindow.document.write("<H2>Windows
properties</H2>")
outputWindow.document.write("Frames:
"+frames.length+'<BR>')
outputWindow.document.write("URL:"+location.href+'<BR>')
}
function describeDocument()
{
outputWindow.document.write("<H2>Document
properties</H2>")
describeLinks()
describeForms()
}
function describeLinks ()
{
outputWindow.document.write("<H3>Links</H3>")
outputWindow.document.write("this document contains
"+document.links.length+ " links"+ "<BR>")
for(i=0; i<document.links.length;i++)
outputWindow.document.write(document.links[i].href+
'<BR>')
}
function describeForms ()
{
outputWindow.document.write("<H3>Forms</H3>")
for(i=0;i<document.forms.length;i++)
describeFrm(i)
}
function describeFrm(n)
{
outputWindow.document.write("Form "+n+" has
"+document.forms[n].elements.length+" elements"+'<BR>')
for(j=0;j<document.forms[n].elements.length;j++)
{

outputWindow.document.write(document.forms[n].elements[j].name)
outputWindow.document.write('<BR>')
}
}
function finishWindow()
{
outputWindow.document.write("<FORM><INPUT TYPE='button'
VALUE='Close Window' ONCLICK= 'window.close()'></FORM>")
outputWindow.document.write("</BODY></HTML>")
}
</script>
</HEAD>
<BODY>
<H1>Using hierarchial Object Identifiers </H1>
<A HREF= http://www.cmcnet.com>Go to CMC's Web Site</A>
<BR>
<A HREF= http://www.netscape.com>Go to Netscape's Web Site</A>
<FORM>
<INPUT TYPE= "text" NAME="textfield1" VALUE= "Enter your text here">
<BR>
<INPUT TYPE= "checkbox" NAME="checkbox1">I am checkbox1
<BR>
<INPUT TYPE= "checkbox" NAME="checkbox2">I am checkbox2
<BR>
<INPUT TYPE= "submit" NAME="submitbutton" VALUE="Submit the
form">
</FORM>
<SCRIPT>
setupWindow()
describeBrowser()
describeWindow()
describeDocument()
finishWindow()
</SCRIPT>
</BODY>
</HTML>
Hierarchical.html
• Methods of Date objects
(The methods with UTC in their names refer to Universal Coordinated Time which is
the time set by the World Time Standard)
Method Description
getDate() Returns or sets the day of the month of the Date object
getUTCDate()
setDate()
setUTCDate()
getDate() Returns the day of week of the Date object
getUTCDate()
getHours() Returns or sets the hour of the Date object
getUTCHours()
setHours()
setUTCHouse()
getMilliseconds() Returns or sets the milliseconds of the Date object
getUTCMilliseconds()
setMilliseconds()
setUTCMilliseconds()
getMinutes() Return or sets the minutes of the Data object
getUTCMinutes()
setMinutes()
setUTCMinutes()
getMonth() Returns or sets the month of the Data object
getUTCMonth()
setMonth()
setUTCMonth()
getSeconds() Returns or sets the seconds of the Date object.
getUTCSeconds()
setSeconds()
setUTCSeconds()
getTime() Returns or sets the time of the Date object
setTime()
getYear() Returns or sets the year of the Date object. The full year method uses the
Method Description
getFullYear() four-digit values.
getUTCFullYear()
setYear()
setFullYear()
setUTCFullYear()
toGMTString() Converts a date to a string in Internet GMT (Greenwich mean Time) format
toUTCString() Returns a string that represents the time in UTC
2. Other predefined object types

2.1 The Array Object

• Two important functions are


1. sort() function – sorts the elements of the Array object
2. reverse() function – reverses the elements of the Array object

• An example to illustrate the use of Array objects


<HTML>
<HEAD>
<TITLE>
Using the Array object
</TITLE>
<SCRIPT>
myArray = new Array()

2.2 The Data Object

• Date constructs
Constructor Description
Date() Creates a Date instance with the current date and time
Date (year, month, Creates a Date instance with the date specified by the
day, hours, year, months, day, hours, minutes, seconds, milliseconds
minutes, seconds, integers. The year and month parameters must be
milliseconds) supplied. If other parameters are included, then all
preceding parameters must be supplied.

• An illustrative example to illustrate the use of Date objects


<HTML>
<HEAD>
<TITLE>Using Date objects</TITLE>
<SCRIPT>
function display(x)
{
document.write(x.getDate()+"/"+(x.getMonth()+1)+ "/"+x.getYear()+"
"+x.getDay()+" ")
document.write(x.getHours()+":"+(x.getMinutes()+1)+
":"+x.getSeconds()+":"+x.getMilliseconds()+'<BR>')
}
d = new Date()
display(d)
document.write("After d.setDate(16)"+'<BR>')
d.setDate(16)
display(d)
document.write("After d.setMonth(10)"+'<BR>')
d.setDate(10)
display(d)
document.write("After d.setYear(2001)"+'<BR>')
d.setYear(2001)
display(d)
document.write("After d.setHours(8)"+'<BR>')
d.setHours(8)
display(d)
document.write("After d.setMinutes(55)"+'<BR>')
d.setMinutes(55)
display(d)
document.write("After d.setSeconds(8)"+'<BR>')
d.setSeconds(8)
display(d)
document.write("After d.setMilliseconds(100)"+'<BR>')
d.setMilliseconds(100)
display(d)
</SCRIPT>
</HEAD>
</HTML>
date.html

2.3 The Math object


• Math properties
Property Description
E Euler’s constant
LN2 The natural logarithm of 2
LN10 The natural logarithm of 10
LOG2E The base 2 logarithm of e
Log10E The base 10 logarithm of e
PI The constant pi
SQRT2 The square root of 2

• Math methods
Methods Description
abs(x) Returns the absolute value of x
acos(x) Returns the arc cosine of x in radians
asin(x) Returns the arc sine of x in radians
atan(x) Returns the arc tangent of x in radians
atan2(x,y) Returns the angle of the polar coordinate corresponding to (x,y)
ceil(x) Returns the least integer that is greater than or equal to x
cos(x) Returns the cosine of x
exp(x) Returns xy
floor(x) Returns the greatest integer that is less than or equal to x
log(x) Returns the natural logarithm of x
max(x,y) Returns the greater of x and y
min(x,y) Returns the lesser of x and y
pow(x,y) Returns xy
random() Returns a random number between 0 and 1
sin(x) Returns the sine of x
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of x

• An example to illustrate the use of Math objects

<HTML>
<HEAD>
<TITLE>
Using the Math objects
</TITLE>
</HEAD>
<BODY>
<H1>Using the Math object</H1>
<SCRIPT>
document.write(Math.PI+"<BR>")
document.write(Math.E+"<BR>")
document.write(Math.ceil(1.234)+"<BR>")
document.write(Math.random()+"<BR>")
document.write(Math.sin(Math.PI/2)+"<BR>")
document.write(Math.min(100,1000)+"<BR>")
</SCRIPT>
</BODY>
</HTML>
math.html
2.4 The String objects
• Allows strings to be accessed as objects
• Length property identifies the string’s length
• String methods

Methods Description
charAt(index) Returns a string that consists of the character at the
specified index of the string to which the method is
applied.
charCodeAt(index) Returns the Unicode encoding of the character at the
specified index
formCharCode(codex) Creates a string from a comma separated sequence of
character codes
indexOf(pattern) Returns the index of the string specified by the pattern
parameter that is contained in the sting. Returns – 1 if
the pattern is not contained in the string.
indexOf(pattern, Same as the previous method except that searching starts
startIndex) at the position specified the starIndex
lastIndexOf(pattern) Returns the index of the last string specified by the
pattern parameter that is contained in the string. Returns
– 1 if the pattern is not contained in the string.
lastIndexOf(pattern, Same as previous method except that searching starts at
starIndex) the position specified as startIndex
split(separator) Separates a string into an array of substrings based upon
the separator
Substring(starIndex) Returns the substring of a string beginning with
startIndex.
Substring(starIndex, Returns the substring of a string beginning with
endIndex) starIndex and ending with endIndex.
toLowerCase() Returns a copy of the string converted to lower case
toUpperCase() Returns a copy of the string converted to upper case
• An example to illustrate the use of String objects

<HTML>
<HEAD>
<TITLE>
Using the String Objects Type
</TITLE>
</HEAD>
<BODY>
<SCRIPT>
function displayLine(text)
{
document.write(text+ '<BR>')
}
s=new String("This is a test of the JavaScript String Methods")
displayLine('s='+s)
displayLine('s.charAt(1)='+s.charAt(1))
displayLine('s.charCodeAt(1)='+s.charCodeAt(1))
displayLine('s.indexOf("is")='+s.indexOf("is"))
displayLine('s.lastIndexOf("is")='+s.lastIndexOf("is"))
displayLine('s.substring(22,32)='+s.substring(22,32))
displayLine('s.toLowerCase()='+s.toLowerCase())
displayLine('s.toUpperCase()='+s.toUpperCase())
split=s.split(" ")
for(i=0;i<split.length;i++)
displayLine('split['+i+']='+split[i])
</SCRIPT>
</BODY>
</HTML>
string.html

You might also like