Professional Documents
Culture Documents
Programming
Language
U. K. Roy
Role of JavaScript
HTML
Purpose → tell the browser how a document should
appear
Static → can view or print (no interaction)
JavaScript Programming Language
Developed by Netscape for use in Navigator Web
Browsers
Purpose → make web pages (documents) more
dynamic and interactive
Change contents of document, provide forms and controls,
animation, control web browser window, etc.
Literals
Operators
Control Structures
Array
Functions
Objects
type typeof
object 'object'
function 'function'
array 'object'
number 'number'
string 'string'
boolean 'boolean'
null 'object'
undefined 'undefined'
©U.K.R., 2008 JavaScript 18
Variables (Cont.)
Using var to declare a variable results in a
local variable (inside a function).
for-loop
break, continue
for/in
do/while; while
Closure
The scope that an inner function enjoys continues even after the
parent functions have returned.
This is called closure.
for(i in circle)
document.writeln(circle[i]);
©U.K.R., 2008 JavaScript 36
Adding new properties
function ComputeArea() {
return (3.14159 * this.radius* this.radius);
}
function Circle(x, y, r) {
this.x_coord = x; this.y_coord = y; this.radius = r;
this.ComputeArea = ComputeArea;
}
var c = new Circle(1, 2, 3);
alert("Area of the circle = " + c.ComputeArea() );
Example
function computePerimeter() {
return 2*3.141*this.radius;
}
c = new Circle(2, 3, 10); d = new Circle(4, 5, 6);
d.computePerimeter = computerPerimeter;
document.writeln(d.computerPerimeter()); //OK
document.writeln(c.computerPerimeter()); //error
function Sales(t) {
this.territory = t;
}
Sales.prototype = new Company();
c = new Company();
s = new Sales("India");
Properties
constructor
Methods
toString
valueOf
Objects as associative arrays
obj.property
obj[“property”]
db = new Array();
db["abc"] = "abc123";
db["xyz"] = "xyz123";
db["user1"] = "user1";
for(i in db)
document.writeln(i+" "+db[i]+"<br>");
username=prompt("UserName","");
passwdgiven = prompt("password","");
if(db[username] == passwdgiven)
alert('ok');
else alert('error');
©U.K.R., 2008 JavaScript 49
Application
db = new Array();
db["abc"] = "abc123";
db["xyz"] = "xyz123";
db["user1"] = "user1";
for(i in db)
document.writeln(i+" "+db[i]+"<br>");
username=prompt("UserName","");
passwdgiven = prompt("password","");
if(db[username] == passwdgiven)
alert('ok');
else alert('error');
©U.K.R., 2008 JavaScript 50
Application
colors[“black”] = “#000000”
colors[“red”] = “#FF0000”
colors[“green”] = “#00FF00”
colors[“blue”] = “#0000FF”
colors[“magenta”] = “#FF00FF”
colors[“yellow”] = “#FFFF00”
colors[“cyan” = “#00FFFF”
colors[“white”] = “#000000”
for(t in colors)
document.writeln(colors[i]);
©U.K.R., 2008 JavaScript 53
Built-in Objects
Array
Methods: length, reverse, concat, sort, push, pop
String
Methods: charAt, length, indexOf, substr
Date
Methods: get/set Day, Month, Year, Hours, Minutes,
Seconds
Regular Description
Expression
Regular Description
Expression
\i Case insensitive
function isNumber(str) {
isprice = /^\d*\.?\d+$/;
return isprice.test( str );
}
function isDate(str) {
isdate = /^\d{4}\-\d{2}\-\d{2}$/;
return isdate.test( str );
}
©U.K.R., 2008 JavaScript 60
Predefined Objects
JavaScript also includes some objects that are
automatically created for you (always
available).
navigator
window
document
screen
<form name="myform">
<input name="aTextBox" type="text">
</form>
<script language="javascript">
function set() {
myform.aTextBox.size = 10;
myform.aTextBox.value = 'Some Text';
}
set();
</script>
focus
Happens when an object becomes active
blur
Happens when focus is lost
click
Happens when an object (such as button, checkbox, reset, submit,
hyperlink) is clicked
mouseOver
Happens when mouse pointer is placed on an object
mouseOut
Happens when mouse pointer is removed
<form name="multiplication">
<input type="text" name="x" size="5">x
<input type="text" name="y" size="5">=
<input type="text" name="result"
size="5"><br>
<input type="button" value="Add"
onClick=“multiply()">
©U.K.R., 2008 JavaScript 72
Events Handlers
‘onSubmit’ event Example
<script language="javascript">
function check() {
return confirm("Do you agree to display
non-secure item?");
}
</script>
focus();
blur()
- This function will take the focus away from the
window
blur();
alert("This is a test");
Prompt
n = prompt(“Enter your name”, “”);
Confirm
msg="Do you want to continue?"
if(confirm(msg))
document.writeln("<h1> Proceed </h1>");
else
document.writeln("<h1> Stop </h1>");
<head>
<script language="javascript">
function check() {
location.href=‘logout.htm';
}
</script>
</head>
<body onLoad=“timeId=setTimeout('check()',50000)">
</body>
clearTimeout(timeID)
- Remove a timeout that was set using the setTimeout function.
<form name="login">
User Id<input type="text" name="userId"><br>
Password<input type="text" name="passwd"><br>
<input type="button" name="submit" value="Submit"
disabled>
</form>
</body>
©U.K.R., 2008 JavaScript 81
moveBy() & moveTo()
moveBy(x,y)
- The window is moved the specified number of pixels
in the X and Y direction.
moveTo(x,y)
- The window is moved to the specified X and Y pixel
location in the browser.
<input type="button"
onClick="moveBy(10,10)"
value="MoveBy">
<input type="button"
onClick="moveTo(0,0)" value="MoveTo">
©U.K.R., 2008 JavaScript 82
open()
Causes to open a new (child) window
open("URLname","WindowName",["options"])
Options
width, height, top, left, resizable, menubar, scrollbar,
toolbar, location, status
<form name="addition">
<input type="button" value="Report"
onClick="showReport()">
</form>
©U.K.R., 2008 JavaScript 84
Multiple windows & frames
Frame within a window is another window
object.
Relationship between multiple frames:
Use of frames[ ], parent, top properties.
Example: frames[1].frames[2], parent.frames[1],
parent.frameName
For a top-level window, parent is equal to self.
<P>This is a paragraph</P>
<P> element node (parent)
|
|
This is a paragraph text node (child)
<P>
____|____
| |
This is a <B>
|
paragraph
<P> ----------------
____|___ |
| | ALIGN
This is a <B> |
| right
paragraph
appendChild()
insertBefore(newChild, refChild)
removeChild(oldChild)
removeNode(boolean removeChildren)
replaceChild(newChild, refChild)
getElementsById(Id)
<P ALIGN="right">This is a <B
ID=“par">paragraph</B></P>
var x = document.getElementById(‘par');
document.getElementById(‘par').firstChild.nodeVal
ue='bold bit of text';
//see example1.htm
©U.K.R., 2008 JavaScript 106
Referring Attributes
Getting all attributes
x.attributes
for(i=0;i<x.attributes.length;i++) {
y = x.attributes[i].nodeValue
}
Getting a specific attribute
element.getAttribute(‘attributeName’);
if(!x.getAttribute(‘align’)) {
//if exists
}
©U.K.R., 2008 JavaScript 107
Referring Attributes
Setting a specific attribute
element.setAttribute(‘attributeName’,’attri
buteValue’);
x.setAttribute(‘align’,’center’);
Removing an attribute
element.removeAttribute(‘attributeName’);
x.removeAttribute(‘align’);
document.createTextNode(text)
var textNode = document.createTextNode('Some
content.');
createAttribute("attributeName")
cloneChild(node)
insertBefore(newElement, targetElement)
insertAfter(newElement, targetElement)
replaceChild(newChildNode, oldChildNode)
theBoldBit.appendChild(theText2);
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
document.body.appendChild(theNewParagraph);
x = document.getElementsByTagName('p')[0];
document.body.removeChild(x);
d.anchors[i]
d.forms[i]
d.forms[i].elements [j]
d.elementName
d.formName.elementName
d.all[i]