Top Banner
Introduction to Java Scripts
90
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Unit2wt

Introduction to Java Scripts

Page 2: Unit2wt

JAVASCRIPT

• JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more.

• JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, Opera.

Page 3: Unit2wt

WHAT IS JAVASCRIPT?• JavaScript is a scripting language (a scripting language is

a lightweight programming language) • A JavaScript is usually embedded directly into HTML

pages • JavaScript is an interpreted language

Page 4: Unit2wt

Are Java and JavaScript the Same?

• NO!• Java and JavaScript are two completely

different languages in both concept and design!

• Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.

Page 5: Unit2wt

How to Put a JavaScript Into an HTML Page?

<html><body><script type="text/javascript">document.write("Hello World!")</script></body></html>

Page 6: Unit2wt

Ending Statements With a Semicolon?

• With traditional programming languages, like C++ and Java, each code statement has to end with a semicolon (;).

• Many programmers continue this habit when writing JavaScript, but in general, semicolons are optional! However, semicolons are required if you want to put more than one statement on a single line.

Page 7: Unit2wt

JavaScript Variables

• Variables are used to store data. • A variable is a "container" for information you want

to store. A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value.

• Rules for variable names:– Variable names are case sensitive – They must begin with a letter or the underscore character

• strname – STRNAME (not same)

Page 8: Unit2wt

JavaScript Operators

Arithmetic OperatorsOperator Description Example Result

+ Addition x=2 4

y=2

x+y

- Subtraction x=5 3

y=2

x-y

* Multiplication x=5 20

y=4

x*y

/ Division 15/5 3

5/2 2,5

% Modulus (division remainder)

5%2 1

10%8 2

10%2 0

++ Increment x=5 x=6

x++

-- Decrement x=5 x=4

x--

Page 9: Unit2wt

JavaScript Operators – 2

Assignment Operators Operator Example Is The Same As

= x=y x=y

+= x+=y x=x+y

-= x-=y x=x-y

*= x*=y x=x*y

/= x/=y x=x/y

%= x%=y x=x%y

Page 10: Unit2wt

JavaScript Operators - 3

Comparison Operators Operator Description Example

== is equal to 5==8 returns false

=== is equal to (checks for both value and type)

x=5

y="5"

 

x==y returns true

x===y returns false

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

>= is greater than or equal to

5>=8 returns false

<= is less than or equal to 5<=8 returns true

Page 11: Unit2wt

JavaScript Operators - 4

Logical Operators Operator Description Example

&& and x=6

y=3

 

(x < 10 && y > 1) returns true

|| or x=6

y=3

 

(x==5 || y==5) returns false

! not x=6

y=3

 

!(x==y) returns true

Page 12: Unit2wt

JavaScript Basic Examples

<script>document.write("Hello World!")</script> <script>alert("Hello World!")</script>

Page 13: Unit2wt

Example

<script>x=“Hello World!”document.write(x)</script>

<script>x=“hai….”document.write(“hello….” +x)</script>

Page 14: Unit2wt

JavaScript Popup Boxes

• Alert Box– An alert box is often used if you want to make sure

information comes through to the user.– When an alert box pops up, the user will have to

click "OK" to proceed.

<script>alert("Hello World!")</script>

Page 15: Unit2wt

JavaScript Popup Boxes - 2

• Confirm Box – A confirm box is often used if you want the user to

verify or accept something.– When a confirm box pops up, the user will have to

click either "OK" or "Cancel" to proceed. – If the user clicks "OK", the box returns true. If the

user clicks "Cancel", the box returns false.

Page 16: Unit2wt

JavaScript Popup Boxes - 3

• Prompt Box– A prompt box is often used if you want the user to

input a value before entering a page.– When a prompt box pops up, the user will have to

click either "OK" or "Cancel" to proceed after entering an input value.

– If the user clicks "OK“, the box returns the input value. If the user clicks "Cancel“, the box returns null.

Page 17: Unit2wt

Prompt Box Example

<script>x=prompt (“enter no”, “ ”)document.write(“number<br>”,+x)</script>

Page 18: Unit2wt

Conditional Statements• Very often when you write code, you want to perform different actions for

different decisions. You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:• if statement - use this statement if you want to execute some code only if

a specified condition is true • if...else statement - use this statement if you want to execute some code

if the condition is true and another code if the condition is false • if...else if....else statement - use this statement if you want to select one

of many blocks of code to be executed • switch statement - use this statement if you want to select one of many

blocks of code to be executed

Page 19: Unit2wt

Conditional Statements - 2if (condition){code to be executed if condition is true

}

if (condition){code to be executed if condition is true}else{code to be executed if condition is not true}

Page 20: Unit2wt

Conditional Statements Examples

<script>x=3if(x<0){alert (“-ve”)}else{alert (“+ve”)}</script>

Page 21: Unit2wt

Conditional Statements Examples - 2

<script>c=confirm(“accept?”)if(c){alert (“accepted”)}else{alert (“rejected”)}</script>

Page 22: Unit2wt

Reading array elements• <html>• <head>• <title>Arrays</title>• <script language="javascript">• var n1=new Array(5);• for(var i=0;i<5;i++)• {• x=window.prompt("<br>enter x")• n1[i]=x;

• document.writeln("<br>"+n1[i]);• }• </script></head><body><br>refresh</body></html>

Page 23: Unit2wt
Page 24: Unit2wt

Ex1:Passing arrays to function<html><head><title>passing arrays to function</title><script language="javascript">var a=new Array(3);var b=new Array();var c=new Array();for(var i=0;i<3;i++){var x=window.prompt("enter x");a[i]=x;document.writeln("<br>first array"+a[i]);}for(i=0;i<4;i++){var y=window.prompt("enter y");b[i]=y;document.writeln("<br>second array"+b[i]);}c=add(a,b);document.writeln("<br>merged array");for(i=0;i<c.length;i++){document.writeln("<br>"+c[i]);}

function add(x,y){var d=new Array();for(var i=0;i<x.length;i++){d[i]=x[i];}for(var j=0;j<y.length;j++){d[i++]=y[j];}

return d;}</script><body><br>refresh</body></

html>

Page 25: Unit2wt
Page 26: Unit2wt

Adding two numbers• <html>• <head>• <title>switch case</title>• <script language="javascript">• var ch;• document.writeln("<br>1.add");• document.writeln("<br>2.sub<br>");• ch=window.prompt("enter your option");• var a=window.prompt("enter firstno");• var b=window.prompt("enter secondno"); • var a1=parseInt(a);• var b1=parseInt(b);• document.writeln("<br> first no is"+a1);• document.writeln("<br> second number

is"+b1);• switch(ch)• {• case "1":

• var c=add(a1,b1);• document.writeln("<br> sum of two

numbers is"+c);• break;• case "2":var c=sub(a1,b1);• document.writeln("<br> diff of two

numbers is"+c);• break;• default:document.writeln("invalid");• break;• }• function add(x,y)• {• return x+y;• }• function sub(x,y)• {• return x-y;• }• </script><body>refresh</body></html>

Page 27: Unit2wt
Page 28: Unit2wt

To find square of an array

• <html>• <head>• <title>hai</title>• <script language="javascript">• var x=4;• for (var i=1;i<=4;i++)• document.writeln(square(i));

• function square(c)• {• return c*c;• }• </script>• </head><body></body></html>

Page 29: Unit2wt

Event handling

• <html>• <head>• <title>events</title>• <script language="javascript">• function fun1()• {• var i=parseInt(abc.txt1.value);• document.writeln("hello"+i*i);• }• </script>• </head>• <body>• <form name="abc">• <input name="txt1" type="text" value="10">• <input type="button" value="square"

onclick="fun1()">• </form></body></html>

Page 30: Unit2wt
Page 31: Unit2wt

31

JavaScript:Objects and Object Models

Page 32: Unit2wt

32

JavaScript: ObjectsOutline• Introduction• Math Object•String Object

• Fundamentals of Characters and Strings• Methods of the String Object• Character-Processing Methods• Searching Methods• Splitting Strings and Obtaining Substrings

•Date Object•Boolean and Number Objects•document Object•window Object

Page 33: Unit2wt

33

Introduction

• Use JavaScript to manipulate every element of XHTML document from a script

Page 34: Unit2wt

34

12.2 Thinking About Objects

• Objects– Attributes– Behaviors– Encapsulate date and methods– Property of information hiding– Details hidden within the objects themselves

Page 35: Unit2wt

DHTML Object Model

applets

all

anchors

embeds

forms

filters

images

links

plugins

styleSheets

scripts

frames

plugins

collection

body

screen

document

history

navigator

location

event

document

document

object

window

Key

Page 36: Unit2wt

13.8 Summary of the DHTML Object Model

Object or collection Description Objects

window Represents the browser window and provides access to the document object contained in the window. If the window contains frames a separate window object is created automatically for each frame, to provide access to the document rendered in the frame. Frames are considered to be subwindows in the browser.

document Represents the XHTML document rendered in a window. The document object provides access to every element in the XHTML document and allows dynamic modification of the XHTML document.

body Provides access to the body element of an XHTML document. history Keeps track of the sites visited by the browser user. The object provides a script

programmer with the ability to move forward and backward through the visited sites, but for security reasons does not allow the actual site URLs to be manipulated.

navigator Contains information about the Web browser, such as the name of the browser, the version of the browser, the operating system on which the browser is running and other information that can help a script writer customize the user’s browsing experience.

location Contains the URL of the rendered document. When this object is set to a new URL, the browser immediately switches (navigates) to the new location.

event Can be used in an event handler to obtain information about the event that occurred (e.g., the mouse x-y coordinates during a mouse event).

screen Contains information about the computer screen for the computer on which the browser is running. Information such as the width and height of the screen in pixels can be used to determine the size at which elements should be rendered in a Web page.

Fig. 13.11 Objects in the Internet Explorer 6 Object Model.

Page 37: Unit2wt

13.8 Summary of the DHTML Object Model

Object or collection Description Collections

all Many objects have an all collection that provides access to every element contained in the object. For example, the body object’s all collection provides access to every element in the body element of an XHTML document.

anchors Collection contains all the anchor elements (a) that have a name or id attribute. The elements appear in the collection in the order they were defined in the XHTML document.

applets Contains all the applet elements in the XHTML document. Currently, the most common applet elements are Java applets.

embeds Contains all the embed elements in the XHTML document.

forms Contains all the form elements in the XHTML document. The elements appear in the collection in the order they were defined in the XHTML document.

frames Contains window objects that represent each frame in the browser window. Each frame is treated as its own subwindow.

images Contains all the img elements in the XHTML document. The elements appear in the collection in the order they were defined in the XHTML document.

links Contains all the anchor elements (a) with an href property. This collection also contains all the area elements that represent links in an image map.

Fig. 13.11 Objects in the Internet Explorer 6 Object Model.

Page 38: Unit2wt

13.8 Summary of the DHTML Object Model

Object or collection Description plugins Like the embeds collection, this collection contains all the embed elements in the

XHTML document. scripts Contains all the script elements in the XHTML document.

styleSheets Contains styleSheet objects that represent each style element in the XHTML document and each style sheet included in the XHTML document via link.

Fig. 13.11 Objects in the Internet Explorer 6 Object Model.

Page 39: Unit2wt

39

String Object

• JavaScript’s string and character-processing capabilities

• Appropriate for processing names, addresses, credit card information, etc.– Characters

• Fundamental building blocks of JavaScript programs

– String• Series of characters treated as a single unit

Page 40: Unit2wt

40

Methods of the String Object Method Description charAt( index ) Returns a string containing the character at the specified index. If there is no

character at the index, charAt returns an empty string. The first character is located at index 0.

charCodeAt( index ) Returns the Unicode value of the character at the specified index. If there is no character at the index, charCodeAt returns NaN (Not a Number).

concat( string ) Concatenates its argument to the end of the string that invokes the method. The string invoking this method is not modified; instead a new String is returned. This method is the same as adding two strings with the string concatenation operator + (e.g., s1.concat( s2 ) is the same as s1 + s2).

fromCharCode( value1, value2, )

Converts a list of Unicode values into a string containing the corresponding characters.

indexOf( substring, index )

Searches for the first occurrence of substring starting from position index in the string that invokes the method. The method returns the starting index of substring in the source string or –1 if substring is not found. If the index argument is not provided, the method begins searching from index 0 in the source string.

lastIndexOf( substring, index )

Searches for the last occurrence of substring starting from position index and searching toward the beginning of the string that invokes the method. The method returns the starting index of substring in the source string or –1 if substring is not found. If the index argument is not provided, the method begins searching from the end of the source string.

String object methods.

Page 41: Unit2wt

41

Methods of the String Objectslice( start, end ) Returns a string containing the portion of the string from index start

through index end. If the end index is not specified, the method returns a string from the start index to the end of the source string. A negative end index specifies an offset from the end of the string starting from a position one past the end of the last character (so –1 indicates the last character position in the string).

split( string ) Splits the source string into an array of strings (tokens) where its string argument specifies the delimiter (i.e., the characters that indicate the end of each token in the source string).

substr( start, length )

Returns a string containing length characters starting from index start in the source string. If length is not specified, a string containing characters from start to the end of the source string is returned.

substring( start, end )

Returns a string containing the characters from index start up to but not including index end in the source string.

toLowerCase() Returns a string in which all uppercase letters are converted to lowercase letters. Non-letter characters are not changed.

toUpperCase() Returns a string in which all lowercase letters are converted to uppercase letters. Non-letter characters are not changed.

toString() Returns the same string as the source string. valueOf() Returns the same string as the source string.

String object methods.

Page 42: Unit2wt

42

Methods of the String ObjectMethods that generate XHTML tags

anchor( name ) Wraps the source string in an anchor element (<a></a>) with name as the anchor name.

blink() Wraps the source string in a <blink></blink> element.

fixed() Wraps the source string in a <tt></tt> element.

link( url ) Wraps the source string in an anchor element (<a></a>) with url as the hyperlink location.

strike() Wraps the source string in a <strike></strike> element.

sub() Wraps the source string in a <sub></sub> element.

sup() Wraps the source string in a <sup></sup> element.

Fig. 12.3 String object methods.

Page 43: Unit2wt

43

Character Processing Methods

• charAt– Returns the character at specific position

• charCodeAt– Returns Unicode value of the character at specific position

• fromCharCode– Returns string created from series of Unicode values

• toLowerCase– Returns lowercase version of string

• toUpperCase– Returns uppercase version of string

Page 44: Unit2wt

44

Searching Methods

• indexOf and lastIndexOf– Search for a specified substring in a string

Page 45: Unit2wt

45

Splitting Strings and Obtaining Substrings

• Tokenization– The process of breaking a string into tokens

• Tokens– Individual words– Separated by delimiters

• String.split()• String.substr(start[, length]) and

String.substring(indexA, indexB)

Page 46: Unit2wt

46

XHTML Markup Methods • Anchor

– <a name = “top”> Anchor </a>• Blink

– <blink> blinking text </blink>• Fixed

– <tt> monospaced text </tt>• Strike

– <strike> strike out text </strike>• Subscript

– <sub> subscript </sub>• Superscript

– <sup> superscript </sup>

Page 47: Unit2wt

47

Date Object

• Provides methods for date and time manipulations

Page 48: Unit2wt

48

Date ObjectMethod Description

getDate() getUTCDate()

Returns a number from 1 to 31 representing the day of the month in local time or UTC, respectively.

getDay() getUTCDay()

Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the week in local time or UTC, respectively.

getFullYear() getUTCFullYear()

Returns the year as a four-digit number in local time or UTC, respectively.

getHours() getUTCHours()

Returns a number from 0 to 23 representing hours since midnight in local time or UTC, respectively.

getMilliseconds() getUTCMilliSeconds()

Returns a number from 0 to 999 representing the number of milliseconds in local time or UTC, respectively. The time is stored in hours, minutes, seconds and milliseconds.

getMinutes() getUTCMinutes()

Returns a number from 0 to 59 representing the minutes for the time in local time or UTC, respectively.

getMonth() getUTCMonth()

Returns a number from 0 (January) to 11 (December) representing the month in local time or UTC, respectively.

getSeconds() getUTCSeconds()

Returns a number from 0 to 59 representing the seconds for the time in local time or UTC, respectively.

getTime() Returns the number of milliseconds between January 1, 1970 and the time in the Date object.

getTimezoneOffset() Returns the difference in minutes between the current time on the local computer and UTC—previously known as Greenwich Mean Time (GMT).

setDate( val ) setUTCDate( val )

Sets the day of the month (1 to 31) in local time or UTC, respectively.

Fig. 12.8 Methods of the Date object.

Page 49: Unit2wt

49

12.5 Date ObjectMethod Description

setFullYear( y, m, d ) setUTCFullYear( y, m, d )

Sets the year in local time or UTC, respectively. The second and third arguments representing the month and the date are optional. If an optional argument is not specified, the current value in the Date object is used.

setHours( h, m, s, ms ) setUTCHours( h, m, s, ms )

Sets the hour in local time or UTC, respectively. The second, third and fourth arguments representing the minutes, seconds and milliseconds are optional. If an optional argument is not specified, the current value in the Date object is used.

setMilliSeconds( ms ) setUTCMilliseconds( ms )

Sets the number of milliseconds in local time or UTC, respectively.

setMinutes( m, s, ms ) setUTCMinutes( m, s, ms )

Sets the minute in local time or UTC, respectively. The second and third arguments representing the seconds and milliseconds are optional. If an optional argument is not specified, the current value in the Date object is used.

setMonth( m, d ) setUTCMonth( m, d )

Sets the month in local time or UTC, respectively. The second argument representing the date is optional. If the optional argument is not specified, the current date value in the Date object is used.

setSeconds( s, ms ) setUTCSeconds( s, ms )

Sets the second in local time or UTC, respectively. The second argument representing the milliseconds is optional. If this argument is not specified, the current millisecond value in the Date object is used.

Fig. 12.8 Methods of the Date object.

Page 50: Unit2wt

50

12.5 Date ObjectMethod Description

setTime( ms ) Sets the time based on its argument—the number of elapsed milliseconds since January 1, 1970.

toLocaleString() Returns a string representation of the date and time in a form specific to the computer’s locale. For example, September 13, 2001 at 3:42:22 PM is represented as 09/13/01 15:47:22 in the United States and 13/09/01 15:47:22 in Europe.

toUTCString() Returns a string representation of the date and time in the form: 19 Sep 2001 15:47:22 UTC

toString() Returns a string representation of the date and time in a form specific to the locale of the computer (Mon Sep 19 15:47:22 EDT 2001 in the United States).

valueOf() The time in number of milliseconds since midnight, January 1, 1970.

Fig. 12.8 Methods of the Date object.

Page 51: Unit2wt

51

Math Object

• Allow the programmer to perform many common mathematical calculations

Page 52: Unit2wt

52

Math ObjectMethod Description Example abs( x ) absolute value of x abs( 7.2 ) is 7.2

abs( 0.0 ) is 0.0 abs( -5.6 ) is 5.6

ceil( x ) rounds x to the smallest integer not less than x

ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0

cos( x ) trigonometric cosine of x (x in radians)

cos( 0.0 ) is 1.0

exp( x ) exponential method ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906

floor( x ) rounds x to the largest integer not greater than x

floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0

log( x ) natural logarithm of x (base e)

log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0

max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7 max( -2.3, -12.7 ) is -2.3

Math object methods.

Page 53: Unit2wt

53

Math Objectmin( x, y ) smaller value of x

and y min( 2.3, 12.7 ) is 2.3 min( -2.3, -12.7 ) is -12.7

pow( x, y ) x raised to power y (xy)

pow( 2.0, 7.0 ) is 128.0 pow( 9.0, .5 ) is 3.0

round( x ) rounds x to the closest integer

round( 9.75 ) is 10 round( 9.25 ) is 9

sin( x ) trigonometric sine of x (x in radians)

sin( 0.0 ) is 0.0

sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0

tan( x ) trigonometric tangent of x (x in radians)

tan( 0.0 ) is 0.0

Fig. 12.1 Math object methods.

Page 54: Unit2wt

54

Math ObjectConstant Description Value Math.E Base of a natural

logarithm (e). Approximately 2.718.

Math.LN2 Natural logarithm of 2. Approximately 0.693. Math.LN10 Natural logarithm of 10. Approximately 2.302. Math.LOG2E Base 2 logarithm of e. Approximately 1.442. Math.LOG10E Base 10 logarithm of e. Approximately 0.434. Math.PI —the ratio of a circle’s

circumference to its diameter.

Approximately 3.141592653589793.

Math.SQRT1_2 Square root of 0.5. Approximately 0.707. Math.SQRT2 Square root of 2.0. Approximately 1.414. Fig. 12.2 Properties of the Math object.

Page 55: Unit2wt

55

Boolean and Number Objects

• Object wrappers for boolean true/false values and numbers

Page 56: Unit2wt

56

Boolean and Number ObjectsMethod Description toString() Returns the string “true” if the value of the Boolean object is

true; otherwise, returns the string “false.” valueOf() Returns the value true if the Boolean object is true; otherwise,

returns false. Fig. 12.10 Boolean object methods.

Page 57: Unit2wt

57

Boolean and Number Objects

Method or Property Description toString( radix ) Returns the string representation of the number. The optional radix

argument (a number from 2 to 36) specifies the number’s base. valueOf() Returns the numeric value. Number.MAX_VALUE This property represents the largest value that can be stored in a

JavaScript program—approximately 1.79E+308 Number.MIN_VALUE This property represents the smallest value that can be stored in a

JavaScript program—approximately 2.22E–308

Number.NaN This property represents not a number—a value returned from an arithmetic expression that does not result in a number (e.g., the expression parseInt( "hello" ) cannot convert the string "hello" into a number, so parseInt would return Number.NaN. To determine whether a value is NaN, test the result with function isNaN, which returns true if the value is NaN; otherwise, it returns false.

Number.NEGATIVE_INFINITY This property represents a value less than -Number.MAX_VALUE.

Number.POSITIVE_INFINITY This property represents a value greater than Number.MAX_VALUE.

Fig. 12.11 Number object methods and properties.

Method Description toString() Returns the string “true” if the value of the Boolean object is

true; otherwise, returns the string “false.” valueOf() Returns the value true if the Boolean object is true; otherwise,

returns false. Fig. 12.10 Boolean object methods.

Page 58: Unit2wt

58

document Object

• Manipulate document that is currently visible in the browser window

Page 59: Unit2wt

59

document ObjectMethod or Property Description write( string ) Writes the string to the XHTML document as

XHTML code. writeln( string ) Writes the string to the XHTML document as

XHTML code and adds a newline character at the end.

document.cookie This property is a string containing the values of all the cookies stored on the user’s computer for the current document. See Section 12.9, Using Cookies.

document.lastModified This property is the date and time that this document was last modified.

Fig. 12.12 Important document object methods and properties.

Page 60: Unit2wt

60

window Object

• Provides methods for manipulating browser window

Page 61: Unit2wt

61

window ObjectMethod or Property Description open( url, name, options ) Creates a new window with the URL of the window set to

url, the name set to name, and the visible features set by the string passed in as option.

prompt( prompt, default ) Displays a dialog box asking the user for input. The text of the dialog is prompt, and the default value is set to default.

close() Closes the current window and deletes its object from memory.

window.focus() This method gives focus to the window (i.e., puts the window in the foreground, on top of any other open browser windows).

window.document This property contains the document object representing the document currently inside the window.

window.closed This property contains a boolean value that is set to true if the window is closed, and false if it is not.

window.opener This property contains the window object of the window that opened the current window, if such a window exists.

Fig. 12.14 Important window object methods and properties.

Page 62: Unit2wt

62

Summary of the DHTML Object ModelObject or collection Description Objects

window Represents the browser window and provides access to the document object contained in the window. If the window contains frames a separate window object is created automatically for each frame, to provide access to the document rendered in the frame. Frames are considered to be subwindows in the browser.

document Represents the XHTML document rendered in a window. The document object provides access to every element in the XHTML document and allows dynamic modification of the XHTML document.

body Provides access to the body element of an XHTML document. history Keeps track of the sites visited by the browser user. The object provides a script

programmer with the ability to move forward and backward through the visited sites, but for security reasons does not allow the actual site URLs to be manipulated.

navigator Contains information about the Web browser, such as the name of the browser, the version of the browser, the operating system on which the browser is running and other information that can help a script writer customize the user’s browsing experience.

location Contains the URL of the rendered document. When this object is set to a new URL, the browser immediately switches (navigates) to the new location.

event Can be used in an event handler to obtain information about the event that occurred (e.g., the mouse x-y coordinates during a mouse event).

screen Contains information about the computer screen for the computer on which the browser is running. Information such as the width and height of the screen in pixels can be used to determine the size at which elements should be rendered in a Web page.

Fig. 13.11 Objects in the Internet Explorer 6 Object Model.

Page 63: Unit2wt

63

Summary of the DHTML Object ModelObject or collection Description Collections

all Many objects have an all collection that provides access to every element contained in the object. For example, the body object’s all collection provides access to every element in the body element of an XHTML document.

anchors Collection contains all the anchor elements (a) that have a name or id attribute. The elements appear in the collection in the order they were defined in the XHTML document.

applets Contains all the applet elements in the XHTML document. Currently, the most common applet elements are Java applets.

embeds Contains all the embed elements in the XHTML document.

forms Contains all the form elements in the XHTML document. The elements appear in the collection in the order they were defined in the XHTML document.

frames Contains window objects that represent each frame in the browser window. Each frame is treated as its own subwindow.

images Contains all the img elements in the XHTML document. The elements appear in the collection in the order they were defined in the XHTML document.

links Contains all the anchor elements (a) with an href property. This collection also contains all the area elements that represent links in an image map.

Fig. 13.11 Objects in the Internet Explorer 6 Object Model.

Page 64: Unit2wt

64

Summary of the DHTML Object ModelObject or collection Description plugins Like the embeds collection, this collection contains all the embed elements in the

XHTML document. scripts Contains all the script elements in the XHTML document.

styleSheets Contains styleSheet objects that represent each style element in the XHTML document and each style sheet included in the XHTML document via link.

Fig. 13.11 Objects in the Internet Explorer 6 Object Model.

Page 65: Unit2wt

DHTML with Java Script

1. Object Referencing2. Dynamic Styles3. Dynamic Positioning4. Using Frames Collection5. navigator object

Page 66: Unit2wt

Object Referencing<html><head><title>inner text</title><script language="javascript">function start(){alert(ptext.innerText);ptext.innerText="Mtech";}</script></head><body onload="start()"><p id="ptext">welcome</p></body>

</html>

Page 67: Unit2wt
Page 68: Unit2wt
Page 69: Unit2wt

Dynamic styles

Page 70: Unit2wt

• <html>• <head>• <title>input color</title>• <script language="javascript">• function start()• {• var col=prompt("enter color name");• document.body.style.backgroundColo

r=col;• }• </script>• </head><body

onload="start()"></body></html>

Page 71: Unit2wt
Page 72: Unit2wt
Page 73: Unit2wt

Event Model

• <html>• <head><title>event</title>• <script language="javascript" for="para" event="onclick">• alert("hai");• </script>• </head>• <body>• <p id="para">click on this text</p>• <input type="button" value="press" onclick="alert('button clicked')">• </body></html>

Page 74: Unit2wt
Page 75: Unit2wt
Page 76: Unit2wt
Page 77: Unit2wt

onmousemove• <html>• <head>• <script language="javascript">

• function udt()• {• cor.innerText=event.srcElement.tagName+• "("+event.offsetX+","+event.offsetY+")";• }

• </script></head>• <body onmousemove="udt()">• <span id="cor">(0,0)</span><br>• <img src="weka.gif">

• </body>• </html>

Page 78: Unit2wt
Page 79: Unit2wt
Page 80: Unit2wt

onmouseover event

• <html>• <head>• <script language="javascript“>onimg1=new Image();• img1.src="weka.gif";• img2=new Image();• img2.src="car05.jpg";

• function mover()• {• if(event.srcElement.id=="tc")• {• event.srcElement.src=img2.src;• return;• }• if(event.srcElement.id)• { • event.srcElement.style.color=event.srcElement.id;• } }• function mout()• {• if(event.srcElement.id=="tc")• {• event.srcElement.src=img1.src;• return; }• if(event.srcElement.id)• {• event.srcElement.innerText=event.srcElement.id;• }}• document.onmouseover=mover;• document.onmouseout=mout;

• </script></head>• <body style="background-color:wheat">• Hex codes• <table>• <caption>• <img src="weka.gif" id="tc">• </caption>• <tr>• <td><a id="black">#000000</a>• <td><a id="red">#ff0000</a>• <td><a id="green">#00ff00</a>• <td><a id="blue">#0000ff</a>

• </tr>• <tr>• <td><a id="olive">#808000</a>• <td><a id="puple">#800080</a>• <td><a id="red">#ff0000</a>• <td><a id="silver">#c0c0c0</a>

• </tr>• <tr>• <td><a id="icyan">#000000</a>• <td><a id="teal">#ff0000</a>• <td><a id="yellow">#00ff00</a>• <td><a id="white">#ffffff</a>

• </tr>

• </table>

• </body>• </html>

Page 81: Unit2wt
Page 82: Unit2wt
Page 83: Unit2wt

Filters and Transitions

• Flip filters:flipv and fliph• Tranparency with chroma

filter• Image filters:gray,xray,invert• Adding shadows to text• Text glow• Creating motion and blur• Blend and reveal transitions

Page 84: Unit2wt

• <html>• <head>• <style type="text/css">• </style>• <body>• <table>• <tr>• <td style="filter:flipv">Hello</td></tr></table></body>• </head>• </html>

Page 85: Unit2wt
Page 86: Unit2wt

DATA BINDING• Introduction to Data Binding

Server-side data binding Disadvantages to server-side binding JavaScript client-side data binding DHTML client-side data bindingDHTML Client-Side Data Binding Using tabular data Data consumers and data sources Furniture table example Types of data consumersUsing Data Consumers HTML data binding attributes Using single-value data consumersData Source Objects Introduction to Data Source Objects What do Data Source Objects do? DSO cross-platform capabilities The Tabular Data Control (TDC)Using the TDC Creating the element DataURL and UseHeader parameters Car Catalog using INPUT elements Navigating single-value data Car Catalog with navigation buttons Managing the TDC TDC data file properties Sorting with the TDC Setting Sort in the OBJECT Setting SortColumn with a scriptThis course is distributed with:

Page 87: Unit2wt

Tabular Data Control Example• Tabular Data Control and JavaScript • The tabular data control exposes a few properties and methods for any

client-side language like JavaScript to manipulate. Some of the important ones are:

• recordset : This property creates a reference point to the data file. • EOF : This property is used to check if we have reached the end of the file. • moveFirst() : Point to the first data item (first row). • moveNext() : Point to the next data item from previous position. • moveLast() : Point to the last data item (last row). • ondatasetcomplete : Event handler that fires when the control and its

data has loaded. • In the below example, we'll use JavaScript to reference a TDC's data file,

and display its 2nd row:

Page 88: Unit2wt

• Data3.txt:• name|age ~Premshree

Pillai~|~19~ • ~Bill Gates~|~18~

Page 89: Unit2wt

• Corresponding HTML page:• <OBJECT ID="data3" CLASSID="CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83">• <PARAM NAME="DataURL" VALUE="data3.txt"> <PARAM NAME="UseHeader"

VALUE="TRUE">• <PARAM NAME="TextQualifier" VALUE="~">• <PARAM NAME="FieldDelim" VALUE="|"> • </OBJECT> • <SCRIPT LANGUAGE="JavaScript">• var dataSet=data3.recordset; //Get the complete data record set

dataSet.moveNext(); //Go to next data row • </SCRIPT>• <SPAN DATASRC="#data3" DATAFLD="name"></SPAN>• <SPAN DATASRC="#data3" DATAFLD="age"></SPAN>

The output will be : Bill Gates 18

Page 90: Unit2wt

Output

• Bill Gates 18