2-JavaScript(1)
2-JavaScript(1)
3. Methods - Unique tasks that can be performed on certain Java Script objects
The Browser
Document
<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
<SCRIPT>
<! - -
document.write(“Hello”)
// - - >
</SCRIPT>
<NONSCRIPT>
[Java Script]
</NONSCRIPT>
• 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 nesting rule for quotes – double quotes within single quotes and vice-versa.
• 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.
• 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)
• 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
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
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
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.
Operator Description
&& Logical AND
II Logical OR
! Logical NOT
➢ 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.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.
1 2
3
5
❖ 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.
❖ 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
❖ 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
❖ 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
❖ 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.
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.
<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
<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
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
❖ 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
1. 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.
• 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
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
• 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.
• 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
<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