You are on page 1of 118

JavaScript

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.

©U.K.R., 2008 JavaScript 2


JavaScript Flavors
 JavaScript
 Originally called LiveScript when introduced in
Netscape Navigator
 In Navigator 2.0, name changed to JavaScript
 Current version 1.5
 JScript
 MS version of JavaScript
 Current version 5.5

©U.K.R., 2008 JavaScript 3


JavaScript Standard
 ECMAScript
 International, standardized version (Edition 3)
 Both versions (JavaScript and JScript) conform to
the standard
 Although both have proprietary extensions

©U.K.R., 2008 JavaScript 4


JavaScript Language
 JavaScript
 Two formats:
 Client-side
 Program runs on client (web browser)
 Can save roundtrips between client and server
 Server-side
 Program runs on server
 Proprietary to web server platform

©U.K.R., 2008 JavaScript 5


Client Side JavaScript
 Overview
 Scripting Languages
 Interpreted--not compiled

 Interpreter uses a scripting engine


 Converts code to executable format each time it runs
 Converted when browser loads web document
 Object Based
 Limitations
 Can not access File System
 Can not do Networking

©U.K.R., 2008 JavaScript 6


First JavaScript Program
 The <script> Tag
 JavaScript programs are run from within an HTML
document
 <script> and </script>
 Used to notify the browser that JavaScript statements
are contained within

©U.K.R., 2008 JavaScript 7


First JavaScript Program
 The <script> Tag
 language attribute
 Denotes the scripting language being used
 Default → JavaScript
 Other languages (e.g., VBScript) may be used
 Can also specify script language version
 No space between name and version
 Checked by browser, scripts ignored if browser doesn’t
support version
 For ECMAScript compatible browsers, omit version

©U.K.R., 2008 JavaScript 8


First JavaScript Program
<html>
<head>
<title>My first JavaScript program</title>
</head>
<body>
<script language = "JavaScript"> Java Script Start Tag
document.writeln("Hello world!");
</script>
</body>
</html>

Java Script End Tag

©U.K.R., 2008 JavaScript 9


JavaScript Program
 Two ways to create
 Incorporated directly into an HTML file
 Use <script> tag
 Placed in an external (source) file
 Use .js file containing only JavaScript statements
 Use src attribute of <script> tag to specify source of
JavaScript statements
 Browser ignores any JavaScript statements between <script>
and </script> tags

©U.K.R., 2008 JavaScript 10


JavaScript Program
 Example:
<script language=“JavaScript” src=“c:\source.js”>
</script>
 Using JavaScript source files
 Makes HTML document neater (less confusing)
 Can be shared among multiple HTML files
 Hides JavaScript code from incompatible browsers
 Use a combination of embedded and non–
embedded code for finer granularity

©U.K.R., 2008 JavaScript 11


Adding Comments
 Two types
 Line comments
 // ignore all text to the end of the line
 Block comments
 /* ignore all text between these symbols */

©U.K.R., 2008 JavaScript 12


Browser Incompatibility
 Two methods
 Place JavaScript in external source file
 Enclose the code within HTML comments

<!-- beginning of HTML block comment


end of HTML block comments -->
 Alternate message display
 If browser doesn’t support JavaScript
 Use <noscript> & </noscript> to place alternate
message to users of incompatible browsers

©U.K.R., 2008 JavaScript 13


Where to place?
 JavaScript can be put in the <head> or in the
<body> of an HTML document
 <head> section rendered before <body> section
 JavaScript functions should be defined in the
<head>
 This ensures that the function is loaded before
it is needed
 JavaScript in the <body> will be executed as the
page loads

©U.K.R., 2008 JavaScript 14


JavaScript Elements
 Variables

 Literals

 Operators

 Control Structures
 Array

 Functions

 Objects

©U.K.R., 2008 JavaScript 15


Variables
 Untyped
 Undefined, if not given a value
 Can be declared with var keyword:
var variable = value;
 Example:

var sum; //undefined


var animal = “cat”;
var found = false;
var month = “April”;
var sum = 0;
©U.K.R., 2008 JavaScript 16
Variables (Cont.)
 Can be created automatically by assigning a
value:
variable = value;
 Example:
x = 1;
lang = “JavaScript";
 Can use typeof to discover a variable’s type
var pi = 3.1.41;
var greeting = “Hello World!”;
typeof(pi);
typeof(greeting);
©U.K.R., 2008 JavaScript 17
typeof
 The typeof prefix operator returns a string
identifying the type of a value.

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).

 If you don't use var – the variable is a global


variable.

©U.K.R., 2008 JavaScript 19


Literals
 The typical bunch:
 Numbers 17 123.45
 Strings "Hello Dave"
 Boolean: true false
 Arrays: [1,"Hi Dave",17.234]

©U.K.R., 2008 JavaScript 20


Operators
 Arithmetic operators
 +, -, *, /, %, ++. --,
 String operators:
 +
 Relation operator:
 ==, >, >=, <, <=, !=
 Logical operators:
 &&, ||, !
 Bitwise operators:
 &, |, ^, ~, <<, >>, >>>
 Assignment operators:
 +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, ^=

©U.K.R., 2008 JavaScript 21


Control Structure
 if;if/else
 switch/case

 for-loop
 break, continue
 for/in
 do/while; while

©U.K.R., 2008 JavaScript 22


Arrays
Arrays
 JavaScript has array literals, written with brackets and
commas
 Example: color = ["red", "yellow", "green", "blue"];
 var a = [1, 5, 7, 2];
 Arrays are zero-based: color[0] is "red"
 “empty” element
 Example: color = ["red", , , "green", "blue"];
 color has 5 elements
 Element is undefined unless assigned
 However, a single comma at the end is ignored
 Example: color = ["red", , , "green", "blue”,]; still has 5
elements
©U.K.R., 2008 JavaScript 24
Array Example
var a = [1, 3, 5, 7];
var sum = 0;
for(i = 0; i < a.length; i++)
sum += a[i];
document.writeln(sum);

©U.K.R., 2008 JavaScript 25


Ways to create Arrays
 Using array literal:
var colors = ["red", "green", "blue"];
 Using new Array() to create an empty array:
 var colors = new Array();
 add elements to the array later:
colors[2] = "blue";
• color[0] and color[1] are added automatically
• Using new Array(n) with a single numeric argument to
create an array of that size
 var colors = new Array(3);
 Using new Array(…) with two or more arguments to
create an array containing those values:
 var cars = new Array(“Maruti",“Tata", “Ford");

©U.K.R., 2008 JavaScript 26


Array methods
 length returns number of elements of an array
 reverse reverses array elements
 concat joins two or more arrays
 sort sorts the elements of an array
 push appends one or more element at the end
 pop removes and returns last element
 shift removes and returns first element
 unshift adds one or more element at the beginning

©U.K.R., 2008 JavaScript 27


Functions
Functions
 The keyword function used to define a
function (subroutine):
function add(x,y) {
return(x+y);
}
 The Function( ) constructor
 var f = new Function(“x”, “y”, “return x*y”)
 The constructor expects a number of strings last of
which is the function body

©U.K.R., 2008 JavaScript 29


Functions as data
function square(x) {return x*x;}
 One can store it in a variable.
b = square; c = b(5);
 Functions can be assigned to array elements.
a = new Array(10);
a[0] = square; a[1] = 20;
a[2] = a[0](a[1]);

©U.K.R., 2008 JavaScript 30


Function Literals
 Function literals
var fun = function(x) {return x*x;}
a[0] = function(y) {return y+y;}
 Function constructors and literals give rise to
anonymous functions.
 Examples:
var y = (function f(x) {return x*x;})(10);

©U.K.R., 2008 JavaScript 31


Inner Functions
 Functions do not all have to be defined at the
top level (or left edge).
 Functions can be defined inside of other
functions.
 Scope
 An inner function has access to the variables and
parameters of functions that it is contained within.
 This is known as Static Scoping or Lexical Scoping.

©U.K.R., 2008 JavaScript 32


Inner Functions
 Functions do not all have to be defined at the top level (or left
edge).
 Functions can be defined inside of other functions.
 Scope
 An inner function has access to the variables and parameters of
functions that it is contained within.
 This is known as Static Scoping or Lexical Scoping.

 Closure
 The scope that an inner function enjoys continues even after the
parent functions have returned.
 This is called closure.

©U.K.R., 2008 JavaScript 33


Example of Inner Function
 function fade(id) {
 var dom = document.getElementById(id),
 level = 1;
 function step () {
 var h = level.toString(16);
 dom.style.color =
 '#FF' + h + h + h + h;
 if (level < 15) {
 level += 1;
 setTimeout(step, 100);
 }
 else {
 level=1;
 setTimeout(step, 100);
 }
 }
 setTimeout(step, 100);
 }

©U.K.R., 2008 JavaScript 34


JavaScript
Objects
Objects
 Creating empty objects
var o = new Object();
 Using object literal
var point = {x:0, y:0};
var circle = {x:0, y:0, radius:10};
 Enumeration of properties using for/in
for(i in point)
document.writeln(point[i]);

for(i in circle)
document.writeln(circle[i]);
©U.K.R., 2008 JavaScript 36
Adding new properties

var center = new Object();


center.x = 0;
center.y = 0;
for(i in center)
document.writeln(center[i]);
center.x = 2;
for(i in center)
document.writeln(center[i]);

©U.K.R., 2008 JavaScript 37


Example
var book=new Object();

book.title = "Java script Book";

book.chapter1 = new Object();


book.chapter1.title = "Introduction";
book.chapter1.pages = 25;

book.chapter2 = {title:"Basics", pages:10};

alert("Outline: " + book.title + "\n\t" +


"Chapter 1 " + book.chapter1.title +"\n\t"
+ "Chapter 2 " + book.chapter2.title);

©U.K.R., 2008 JavaScript 38


Constructor
 It is a function which is invoked through new operator.
function Circle(x, y, r) {
this.x_coord = x;
this.y_coord = y;
this.radius = r;
}
var c = new Circle(1, 2, 3);
 It is passed a reference to a newly created empty object as the value
of a special “this” keyword.
 It is an initializer
 Constructors typically do not have a return value.

©U.K.R., 2008 JavaScript 39


Adding new methods

 Define new functions


 These functions typically operate on “this” object.
 Associate the functions as a method in an
object.
 In the constructor of an object, make these
associations.
 Such a technique of defining method is space
inefficient.

©U.K.R., 2008 JavaScript 40


Example

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() );

©U.K.R., 2008 JavaScript 41


Setting properties
 Properties and methods can be added in object
basis
function computeArea() {
return 3.141*this.radius*this.radius;
}
function Circle(x, y, r) {
this.x = x; this.y = y; this.radius = r;
this.computeArea = computeArea;
}
c = new Circle(2, 3, 10); d = new Circle(4, 5, 6);
c.color = “red”;
document.writeln(c.color); //OK
document.writeln(d.color); //error

©U.K.R., 2008 JavaScript 42


Setting methods

 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

©U.K.R., 2008 JavaScript 43


Prototype Object
 Example
 A constructor function contains a prototype
object.
 Each object initialized by one constructor
inherits/shares the same prototype object.
function ComputeArea()
{
return (this.PI * this.radius* this.radius);
}
Circle.prototype.PI = 3.14159;
Circle.prototype.ComputeArea = ComputeArea;
Circle.prototype.ComputePerimeter = ComputePerimeter;
©U.K.R., 2008 JavaScript 44
Prototype

 Prototype properties cannot be written by an


object.
 Methods may be set to the properties of the
prototype.
 Prototype is also an object and so, it inherits
prototype object of the “object” class by default.

©U.K.R., 2008 JavaScript 45


Inheritance
function Company() {
this.name = "Hardware";
}

function Sales(t) {
this.territory = t;
}
Sales.prototype = new Company();

c = new Company();
s = new Sales("India");

document.writeln(c.name+" "+s.name+" "+s.territory);

©U.K.R., 2008 JavaScript 46


The Object

 Properties
 constructor
 Methods
 toString
 valueOf
 Objects as associative arrays
 obj.property
 obj[“property”]

©U.K.R., 2008 JavaScript 47


Associative Array Example

circle = new Object();


circle["x"] = 2;
circle.y = 3;
circle["radius"] = 4;
document.writeln(circle.x+"
"+circle["y"]+" "+circle["radius"]);

©U.K.R., 2008 JavaScript 48


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 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

neighbors = new Object();


neighbors[3] = true;
neighbors[80] = true;
neighbors[4] = true;
if(neighbors[2] == true)
alert('neighbor');
else
alert('not a neighbor');

©U.K.R., 2008 JavaScript 51


Application

neighbors = new Object();


neighbors[3] = true;
neighbors[80] = true;
neighbors[4] = true;
if(neighbors[2] == true)
alert('neighbor');
else
alert('not a neighbor');

©U.K.R., 2008 JavaScript 52


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

©U.K.R., 2008 JavaScript 54


Regular
Expression
Regular expression

 A pattern user for


 Validation
 Search & Replace
Regular Description
Expression

\d Matches any digits- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9


\w Matches and letter (either case), number or
underscore.
\s Matches any of the white space characters such as
space, tab and new line

. Matches any character except a new line


©U.K.R., 2008 JavaScript 56
Regular expression

Regular Description
Expression

{x} Matches x occurrences of pattern


{x, y} Matches at least x but not more than y occurrences of
the pattern
{x,} Matches at least x occurrences of pattern with no upper
limit

? Matches none or one occurrence of the pattern


+ Matches one or more occurrence of the pattern
* Matches none or more occurrence of the pattern

©U.K.R., 2008 JavaScript 57


Regular expression

Regular Description
Expression

/^ Start of string or line


$/ End of string or line

\<special Matches a special character such as new line (\n), tab


character> (\t) or a character that is a part of the syntax (e.g. {)

\i Case insensitive

©U.K.R., 2008 JavaScript 58


Regular expression

Description Regular Expression

Floating point number /^\d*\.?\d+$/


Integer /^\d+$/
Date /^\d{4}\-\d{2}\-\d{2}$/
(yyyy-mm-dd)

©U.K.R., 2008 JavaScript 59


Examples

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

©U.K.R., 2008 JavaScript 61


JavaScript Object Hierarchy

©U.K.R., 2008 JavaScript 62


Accessing objects
 JavaScripts objects are accessed as:
 parent.childName
 parent.[“childName”]
 parent.[indexOfChild]
 getElementById(elementId)

©U.K.R., 2008 JavaScript 63


Example

<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>

©U.K.R., 2008 JavaScript 64


Example
<form name="myform">
<input name="aButton" type="button" value="ClickMe">
</form>
<script language="javascript">
function display() {
document.writeln('value ='+myform.aButton.value+'<br>');
document.writeln('name = '+myform.aButton.name+'<br>') ;
document.writeln('value = '+myform[0].value+'<br>');
document.writeln('value = '+myform["aButton"].value);
}
display();
</script>

©U.K.R., 2008 JavaScript 65


JavaScript Events
 JavaScript supports an event handling system.
 You can tell the browser to execute javascript
commands when some event occurs.
 Sometimes the resulting value of the command
determines the browser action.

©U.K.R., 2008 JavaScript 66


Events example
 load
 Happens when an object (document) is loaded

 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

©U.K.R., 2008 JavaScript 67


Events example
 change
 An element lost the focus when it was changed
 reset
 Happens when an object (usually a form) is reset
 submit
 User submitted an object (usually a form)
 select
 Some text is selected
 abort
 User action caused an error
 Error
 An error occurred
 unload
 Object was exited
©U.K.R., 2008 JavaScript 68
Events Handlers
 Event handlers are created as follows:
onEvent = "Code to handle the event"
 ‘onLoad’ event Example
<script language = "JavaScript">
function inform() {
alert('You are using
'+navigator.appName+navigator.appVersion);
}
</script>
<body onLoad="inform()">
</body>

©U.K.R., 2008 JavaScript 69


Events Handlers
 ‘onClick’ event Example

<script language = "JavaScript">


function handler() {
alert('I said not to click me');
}
</script>
<input type="button" value="Don't click me"
onClick="handler()">

©U.K.R., 2008 JavaScript 70


Events Handlers
 ‘onMouseOver’ and ‘onMouseOut’ events Example

<script language = "JavaScript">


function handCursor(o) {
o.style.cursor='hand';
o.style.color='red';
}
function normalCursor(o) {
o.style.color='black';
}
</script>
<a onMouseOver="handCursor(this)"
onMouseOut="normalCursor(this)">Library</a>
©U.K.R., 2008 JavaScript 71
Events Handlers
 ‘onClick’ event Example
<script language = "JavaScript">
function multiply() {
with(document.multiplication) {
result.value=x.value * y.value;
}
}
</script>

<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>

<form name="myform" action="eventHandling.htm"


onSubmit="return check()">
<input name="aButton" type="submit"
value="ClickMe">
</form>

©U.K.R., 2008 JavaScript 73


Window Object
 Properties

name name of the window


opener object caused to open this window
document document currently being displayed
frames[] list of windows opened from this window
location location object that represents current URL
status status bar
parent parent window of the current window
self the current window
top top window in a list of framed windows

©U.K.R., 2008 JavaScript 74


Window Object Properties (Contd.)
 Properties

closed A Boolean value that indicates whether the window is


closed
history list of URLs that the current window has loaded
screen screen object

©U.K.R., 2008 JavaScript 75


Window Object Methods
 focus(), blur()
 alert(), prompt(), confirm()
 setTimeOut(), clearTimeOut()
 setInterval(), clearInterval()
 moveBy(), moveTo()
 resizeBy(), resizeTo()
 open(), close()

©U.K.R., 2008 JavaScript 76


Window Object Methods
 focus()

This function will give the focus to the window

focus();

 blur()
- This function will take the focus away from the
window

blur();

©U.K.R., 2008 JavaScript 77


Dialog Examples
 alert("message")
- The string passed to the alert function is displayed in an alert
dialog box.

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>");

©U.K.R., 2008 JavaScript 78


setTimeout() & clearTimeout()
 setTimeout(code, timeout)
- Used to call a function after the specified time in milliseconds.

<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.

©U.K.R., 2008 JavaScript 79


setInterval() & clearInterval()
 Sometimes want something to occur periodically.
 setInterval(code_string, interval)
- Causes code_string to be called periodically
- code_string—typically a function but can be any legal JavaScript
code.
- Interval—specified in milliseconds.
<head>
<script language="javascript">
function showTime(){
status = new Date();
}
</script>
</head>
<body onLoad=“timeID=setInterval(‘showTime()',1000);">
 clearInterval(timeID)
- Removes a repetitive timeout that was set up using the setInterval
function.
©U.K.R., 2008 JavaScript 80
setInterval()— another example
<body onLoad="setInterval('check()',100)">
<script language="javascript">
function check() {
with(document.login) {
if(userId.value != "" && passwd.value != "")
document.login.submit.disabled=false;
if(userId.value == "" || passwd.value == "")
submit.disabled=true;
}
}
</script>

<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

©U.K.R., 2008 JavaScript 83


open()—example
<script language = "JavaScript">
function showReport() {
win=open("report.htm","test",
"toolbar=no,menubar=no,width=600,height=
400,resizable=no");
}
</script>

<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.

©U.K.R., 2008 JavaScript 85


Multiple windows & frames
 Each window and frame defines an
independent execution context.
 Script in one frame can use variables and
functions defined in script of another frame.
 Example
 parent.frames[0].i = 4;
 parent.frames[0].f( )

©U.K.R., 2008 JavaScript 86


Multiple windows example
 <!– multipleWindows.htm-->

©U.K.R., 2008 JavaScript 87


The location object
 Properties
 href entire URL
 protocol URL protocol name including ‘:’
 hostname URL host section
 host URL hostname and port
 port URL port section
 pathname URL pathname section
 search URL query string section
 Methods
 reload() current window document is reloaded
 replace(URL) not placed in history object

©U.K.R., 2008 JavaScript 88


Location example
<!—location1.jsp -->
<script language="javascript">
function logout() {
if(confirm("Are you sure to
logout?"))
location.href='logout.jsp';
}
</script>
<input type="button" value="Logout"
onClick="logout()">
©U.K.R., 2008 JavaScript 89
The history object
 Properties
 current - The current document URL.
 length - The number of entries in the history object.
 next - The URL of the next document in the history object.
 previous - The URL of the last document in the history object
 Methods
 back() - Go to the previous URL entry in the history list
<INPUT TYPE="button" VALUE="Go Back"
onClick="history.back()">
 forward() - Go to the next URL entry in the history list
<INPUT TYPE="button" VALUE="Go Forward"
onClick="history.forward()">
 go(relPos | string)
<INPUT TYPE="button" VALUE="Go Back"
onClick="history.go(-1)">

©U.K.R., 2008 JavaScript 90


Document Object
 document object implements DOM
 Documentinterface
 HTMLDocument interface

 But it also supports methods and properties not


part of the DOM specification.
 While not standardized, widely supported by
JavaScript implementations in most browsers.

©U.K.R., 2008 JavaScript 91


Document Object
 Predefined object: document
 document properties
 alinkColor,
 vlinkColor,
 bgColor,
 fgColor,
 linkColor,
 title,
 URL,
 forms[],
 images[],
 anchors[]
©U.K.R., 2008 JavaScript 92
write() and writeln()
 Helpful for generating portions of the document
dynamically.
 Inserts text as part of the document as it is being
parsed.
 Writing can be done only from within <Script> tags.
 Writing the document from an event handler
overwrites the current document instead of appending
to it.
 This is often a lot easier than creating DOM nodes and
manipulating DOM tree.
 But, it only works during the initial parse.
 If you need to insert, rearrange, and otherwise modify
content after the page is loaded, you need the DOM
interfaces.
©U.K.R., 2008 JavaScript 93
The Document Object Model
A standard to describes the structure and style
of documents (HTML, XML and others)
 Standardized by W3C

 programmers can build documents, navigate


their structure, and add, modify, or delete
elements and content
 Platform and Language neutral—designed to
interact with many programming languages.

©U.K.R., 2008 JavaScript 94


The Document Object Model
 Itviews HTML documents as a family tree-like
structure of elements and text, embedded
within other elements
 Elements (almost every), the text they contain
and their attributes can be referenced by
walking through the DOM tree
 New elements can be created, contents can be
modified and deleted on the fly

©U.K.R., 2008 JavaScript 95


The Document Object Model
 Each object is a Node

<P>This is a paragraph</P>
<P> element node (parent)
|
|
This is a paragraph text node (child)

©U.K.R., 2008 JavaScript 96


Nodes
<P>This is a <B>paragraph</B></P>

<P>
____|____
| |
This is a <B>
|
paragraph

©U.K.R., 2008 JavaScript 97


Attribute Node
<P ALIGN="right">This is a <B>paragraph</B></P>

<P> ----------------
____|___ |
| | ALIGN
This is a <B> |
| right
paragraph

©U.K.R., 2008 JavaScript 98


The entire document
<P ALIGN="right">This is a
<B>paragraph</B></P>
<HTML>
_________|_________
| |
<BODY> <TITLE>
| |
<P> ---------------- My home page
_____|____ |
| | ALIGN
This is a <B> |
| right
paragraph
©U.K.R., 2008 JavaScript 99
Another example
 <p title="The test paragraph">This is a sample of some <b>HTML you
might<br>have</b> in your document</p>
p
_______________|________________
| |
childNodes attributes
________|_______________ |
| | | title = 'The test paragraph'
'This is a sample of some' b 'in your document'
|
childNodes
__________|_______
| | |
'HTML you might' br 'have'

©U.K.R., 2008 JavaScript 100


Walking through the DOM tree
 Suppose x points to <P>
x.parentNode //<BODY>
x.childNodes[1]/x.childNodes.item(1) //<B>
x.firstChild
x.lastChild
x.previousSibling
x.nextSibling
document.firstChild.firstChild.lastChild //<B>
document.firstChild.childNodes[0].lastChild //<B>
document.firstChild.childNodes[0].childNodes[1]
//<B>

©U.K.R., 2008 JavaScript 101


Special Elements
document.documentElement //<HTML>
document.body //<BODY element>

©U.K.R., 2008 JavaScript 102


Node properties
 nodeName
 tagName
 nodeType
 1an element
 2an attribute
 1a text
 nodeValue
 null for element node
 text for text node
 value of attribute for attribute node
 attributes
 childNodes
 parentNode

©U.K.R., 2008 JavaScript 103


Node methods
 hasChildNodes()

 appendChild()

 insertBefore(newChild, refChild)
 removeChild(oldChild)

 removeNode(boolean removeChildren)
 replaceChild(newChild, refChild)

©U.K.R., 2008 JavaScript 104


Referring text nodes
 Reading node value
element.nodeValue
alert(‘theParagraph.childNodes[1].firstChild.node
Value’);
 Setting node value
 theParagraph.childNodes[1].firstChild.nodeValue
=‘bold bit of text’;

©U.K.R., 2008 JavaScript 105


Getting an element
 getElementsByTagName(tagName)
 Returns array of all tags
var x = getElementByTagName(‘B’)[0]
var x = getElementByTagName(‘P’)[0].lastChild

 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’);

©U.K.R., 2008 JavaScript 108


Creating nodes
 document.createElement()
var par = document.createElement('p');

 document.createTextNode(text)
var textNode = document.createTextNode('Some
content.');

 createAttribute("attributeName")

 cloneChild(node)

©U.K.R., 2008 JavaScript 109


Adding Inserting nodes
appendChild(newNode)
par.appendChild(text);

insertBefore(newElement, targetElement)

insertAfter(newElement, targetElement)

replaceChild(newChildNode, oldChildNode)

©U.K.R., 2008 JavaScript 110


Creating nodes example
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');

var theText1 = document.createTextNode('This is a');


var theText2 = document.createTextNode(' paragraph');

theBoldBit.appendChild(theText2);

theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);

document.body.appendChild(theNewParagraph);

©U.K.R., 2008 JavaScript 111


Deleting nodes
element.removeChild(referenceToChildNode)

x = document.getElementsByTagName('p')[0];
document.body.removeChild(x);

©U.K.R., 2008 JavaScript 112


HTMLElement
 Any element in the body of a html page is
represented by an object of HTMLElement
class.
 This class is the base of many other classes
such as: Input, Anchor, Document, Form,
Image etc.
 Classes derived from Input class include
CheckBox, Button.

©U.K.R., 2008 JavaScript 113


HTML DOM tree
Node
_________________|_____________
| |
Document Element
| |
HTMLDocument HTMLElement

©U.K.R., 2008 JavaScript 114


HTMLElement:Access
 An HTMLElement is accessed as:
 d.images[i]

 d.anchors[i]

 d.forms[i]

 d.forms[i].elements [j]
 d.elementName

 d.formName.elementName

 d.all[i]

©U.K.R., 2008 JavaScript 115


HTMLElement:Properties, Methods
 IE properties:
 all[ ], children[ ], className, document, id,
innerHTML, innerText, offsetHeight, offsetLeft,
outerText, outerHTML, sourceIndex, style,
tagName
 IE methods
 contains(target), getAttribute(AttribName),
insertAdjacent HTML, insertAdjacentText()

©U.K.R., 2008 JavaScript 116


Changing Content

 Each HTMLElement has a number of properties


 innerText, innerHTML, outerText, outerHTML
 Example
<DIV style = "font-style:italic">
<P Id = par1 STYLE = "font-style:normal">
A fairly short paragraph </p>
<form>
<SCRIPT> var d = document.all.par1 </SCRIPT>
<Input = button value= "Change InnerText"
onClick = "d.innerText = 'How are <B> you</B>'">
<Input = button value= "Change InnerHTML"
onClick = "d.innerHTML = 'How are <B> you</B>'">
</form> </DIV>
©U.K.R., 2008 JavaScript 117
Inserting Content
 Two methods of each element
 insertAdjacentText(where, text)
 insertAdjacentHTML (where, text)

value of where: BeforeBegin, AfterBegin, BeforeEnd,


AfterEnd

©U.K.R., 2008 JavaScript 118

You might also like