1 javascript csc667/867 spring 2005 ilmi yoon. 2 outline basics of javascript, some simple examples...

80
1 JavaScript JavaScript csc667/867 csc667/867 Spring 2005 Spring 2005 Ilmi Yoon Ilmi Yoon

Upload: emma-hart

Post on 04-Jan-2016

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

1

JavaScriptJavaScriptcsc667/867csc667/867Spring 2005Spring 2005

Ilmi YoonIlmi Yoon

JavaScriptJavaScriptcsc667/867csc667/867Spring 2005Spring 2005

Ilmi YoonIlmi Yoon

Page 2: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

2

Outline

• Basics of JavaScript, • Some simple examples• Basics of the language• variables, types, arrays, objects, and

functions

• operators, expressions, strings, and statements

• JavaScript Full Reference at http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/

Page 3: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

3

What is JavaScript•JavaScript is a “simple”, interpreted,

programming language with elementary object-oriented capabilities

•JavaScript has two distinct but overlapping systems

–client-side JavaScript runs on Web browsers–server-side JavaScript runs on Web servers

•Syntactically JavaScript resembles C, C++, Java

•JavaScript was developed by Netscape (formerly called LiveScript)

Page 4: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

4

JavaScript is Embedded in HTML<HTML><HEAD></HEAD><BODY><SCRIPT LANGUAGE=”JavaScript”>//the Javascript here produces content for the BODY on loading</SCRIPT></BODY></HTML>

Deferred Script<HTML><HEAD><SCRIPT LANGUAGE=”JavaScript”>//the Javascript here creates functions for later use </SCRIPT></HEAD><BODY></BODY></HTML>

Page 5: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

5

A Simple Example<HTML>

<HEAD>

<TITLE>Simple Javascript</TITLE>

</HEAD>

<BODY>

<H1>First Example of JavaScript</H1>

<SCRIPT LANGUAGE=”JavaScript”>

<!-- hide from old browsers by embedding in a comment

document.write(“Last updated on “ + document.lastModified

+ “.”)

// end script hiding -->

</SCRIPT>

</BODY>

</HTML>

Page 6: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

6

Example 1: Browser Output

Page 7: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

7

Another Example<HTML>

<HEAD><TITLE>Computing Factorials</TITLE></HEAD>

<BODY>

<H1>Another Example of JavaScript</H1>

<SCRIPT LANGUAGE=”JavaScript”>

document.write(“<H1>Factorial Table</H1>”);

for ( i = 1, fact = 1; i < 10; i++, fact = fact * i) {

document.write(i + “! = “ + fact);

document.write(“<BR>”);

}

</SCRIPT>

</BODY>

</HTML>

Page 8: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

8

Another Example

Page 9: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

9

JavaScript has Event Handlers<HTML>

<HEAD><TITLE>Handling Events Example</TITLE></HEAD>

<BODY>

<H1>Handling Events in JavaScript</H1>

<FORM>

<INPUT TYPE=”button” VALUE=”Click me”

onClick=alert(“You clicked me”) >

</FORM>

</BODY>

</HTML>

Page 10: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

10

Example 3

Page 11: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

11

What JavaScript Programs Can Do

•Write programs to perform any computation; it is equivalent in power to a general purpose programming language

•Control Web page appearance and content (this is its intended use)

•Control the Web browser, open windows and frames

•Interact with document content•Retrieve and manipulate all hyperlinks•Interact with the user•Read/write client state with cookies

Page 12: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

12

JavaScript - The Basics

• JavaScript is case-sensitivesum, SUM and Sum are 3 different identifiers

– HTML is NOT case-sensitive

• JavaScript ignores spaces, tabs, newlines• Semicolon is optional

– but multiple statements on a line require a semicolon

i = 1; j = 2

• C and C++ style comments are supported

//comment to end of line

/* this can be a

multiple line comment */

Page 13: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

13

JavaScript Literals• Literals

– numbers, strings, true, false, null

• All numbers are treated as floating point

base10 [-](1-9)(0-9)*

base8 [-]0(0-7)*

base16 [-]0(x|X)(0-9|a-f|A-F)*

float [(+|-)][digits][.digits][(E|e)[(+|-)]digits]

• There are special numerical constants

Number.MAX_VALUE, Number.MIN_VALUE,

Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY

Page 14: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

14

String Literals• Any sequence of zero or more

characters enclosed within single or double quotes

• Examples– ‘a single quoted string’– “a double quoted string”– “”– “alert(‘Please Click OK’)”

Page 15: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

15

JavaScript Data TypesType Example DescriptionString “a string” a series of characters inside

quote marksNumber 123.45 Any number not

inside quote marksBoolean true a logical true and falseNull null completely devoid of any

value, not a number, not a string, different than 0

in C/C++Object all properties and methods

belonging to the objectFunction a function

Page 16: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

16

JavaScript Arrays and Objects•Arrays

–one dimensional, indexed from zero–array elements can contain any type of data

including references to other arrays, to objects, to functions

–array elements can have different types

•Objects–a collection of data where each item has a name–e.g. document has a property images array whose

elements have properties width and height, e.g. document.images[i].width

Page 17: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

17

Arrays •Elements are normally accessed using []

arr[0] = 1;

arr[arr[0]] = 2;•Arrays in JavaScript are sparse

arr[0] = 1; arr[10000] = “a string”;

only 2 indices are allocated•Arbitrary expressions are permitted in []

frames[i*j+12]

document.frames[i].elements[j++]•Even expressions that evaluate to a string

document[“lastModified”]

Page 18: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

18

Array and Objects

•Objects and arrays are really identicaltypeof(array) = typeof(object) = object

typeof() returns a string which is the type of its argument (“number”, “string”, “boolean, “object”, “function”, “undefined”)•Object elements are accessed using dot (.)•An object/array on the left requires a field name on the right of dot

document.lastModified

frames[0].length•The dot operator can be used with arrays

arr[1] is identical to arr.1but if i = 1, arr[1] is not equivalent to arr.i since

property names are not evaluated

Page 19: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

19

Date: Browser Output

Page 20: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

20

Using alert(), confirm(), and prompt()

<HTML><HEAD><TITLE>Example of alert, confirm, prompt</TITLE>

<SCRIPT LANGUAGE=JavaScript>function alertUser() { alert("An alert box contains an exclamation mark");}function confirmUser() {var msg = "\n please confirm that you want\n" + "to test another button?";if (confirm(msg))

document.write("<h2>You selected OK</h2>");else document.write("<h2>You selected Cancel</h2>"); }function promptUser() {name1=prompt("What is your name?”, “ “); document.write("<h2>welcome to this page " + name1 +

"</h2>"); }</SCRIPT></HEAD>

Page 21: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

21

Using alert(), confirm(), and prompt()

<BODY>welcome to this page<br><FORM><INPUT TYPE=button VALUE="Click here to test

alert()” onClick="alertUser()"><BR><INPUT TYPE=button VALUE="Click here to test

confirm()" onClick="confirmUser()"><BR><INPUT TYPE=button VALUE="Click here to test

prompt()" onClick="promptUser()"></FORM></BODY></HTML>

Page 22: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

22

Clicking on alert()

Page 23: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

23

Clicking on confirm()

Page 24: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

24

Clicking on prompt()

Page 25: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

25

Supporting IE and NS

• IE and NS do not support the same JavaScript language– they include similar/identical capabilities, but the way to invoke them is different

• We must write JavaScript that works across both browsers– if a client gets a JavaScript error it is annoying and there is nothing viewers can do

Page 26: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

26

Determining the Browser• navigator is a built-in object with properties

that describe the browser– defined in both IE and NS– navigator.appName is a string with the browser name

– navigator.appVersion is a string with the version number

– to determine the correct version you may need to convert from string to number

– parseFloat returns a number from a string, and ignores any part of the string after the number

– Number only converts a string that is a number to a number

Page 27: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

27

Determining the Browser<HTML><HEAD><TITLE>Check Browser</TITLE>

</HEAD><BODY>

<SCRIPT language=JavaScript>

document.write(“<BR> This browser is “

+ navigator.appName);

document.write(“<BR> Version “

+ navigator.appVersion);

if (parseFloat(navigator.appVersion) >= 4)

{ document.write(“<BR> You have an up-to-date

browser”); }

</SCRIPT>

</BODY>

</HTML>

Page 28: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

28

Browser Output

Page 29: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

29

Avoiding Errors• Since IE and NS differ somewhat in JavaScript,

it is useful to first check if an object, property or method exists

• One can refer to any name in a conditional and if it is undefined the conditional returns false

newItem = something;//produces an error if

//something is undefined

if ( something ) { newItem = something; }

does not produce an error, but only changes newItem if something exists

Page 30: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

30

Example: Checking Window Size• NS and IE use different object properties to

hold the window size– IE: document.body.clientwidth or clientheight

– NS: window.innerWidth or innerHeight• Suppose you want to vary the response depending

upon the size of the browser window– lets write a program that does this

Page 31: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

31

Re-Direct the Browser<HTML><HEAD><TITLE>re-direct based upon window

size</TITLE></HEAD>

<BODY><SCRIPT language=JavaScript>

function windowHeight( ) {

if (document.body && //test for IE document.body.clientHeight)

{ return document.body.clientHeight;}

else if (window.innerHeight) //test for NS

{ return window.innerHeight; }

else {return 0;}; //both tests have failed

}

if (windowHeight() >= 500) {

document.location = “fancy.html”;}

else {document.location = “lessfancy.html”;};

</SCRIPT></BODY></HTML>

Page 32: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

32

Points to Observe• If the check for IE and NS both fail then a

height of 0 is returned and the lessfancy file is displayed

• The conditional with the && clause is checked left-to-right in short-circuit mode

Page 33: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

33

Example: A Dynamically Changing Banner

• Use JavaScript to have a region where the HTML is dynamic

• use the STYLE attribute to create an HTML block that is accessed by JavaScript

• use a periodically scheduled event

id = setInterval(JSstring, msec);• JSstring is JavaScript code and msec is

milliseconds • JSstring is called every time

Page 34: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

34

Browser Output

Page 35: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

35

HEAD of the banner Example<HTML><HEAD<TITLE>changing banner</TITLE>

<SCRIPT language=JavaScript>

var banners = new Array();

banners[0] = “banner0”;

banners[1] = “banner1”;

banners[2] = “banner2”;

var which = 0;

function update() {

display(“banner”, banners[which]);

which++;

if (which == banners.length) which = 0;

}

…display function

</SCRIPT><BODY>...

Page 36: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

36

What Document HEAD does• Defines array banners of HTML to display• Defines counter, called which, that tells which

element is being displayed• Defines update which calls display() with ID

“banner” and the current element of banners, then increments which

Page 37: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

37

Changing HTML in a Regionfunction display(id, str) {

if (document.all) {

document.all[id].innerHTML=str;}

else {

document[id].document.open();

document[id].document.write(str);

document[id].document.close();

}

Page 38: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

38

BODY of Banner Example<HEAD><TITLE>Varying a Banner</TITLE>

<SCRIPT Language=JavaScript>

function update(){/*load new banner for eachcall*/}

</SCRIPT></HEAD>

<BODY onload= "if (setInterval) { setInterval('update()', 5000);}">

<p>An example of a changing text banner</P>

<P><SPAN ID="banner" STYLE="position:absolute;"><I>

<SCRIPT Language=Javascript>

if (setInterval)

{document.write('the banner is loading');}

else {document.write('Get a new browser');};

</SCRIPT></I></SPAN>

<BR><P>Here is the remainder of the document</P>

</BODY></HTML>

Page 39: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

39

Points to Observe• Uses onload event handler to start a periodic

event with setInterval– runs the function update() every 5 seconds– update must be defined in the HEAD– does nothing if setInterval is not defined

• Uses an HTML SPAN tag to define the element that the update function will change– has an ID (similar to a name, but for all tags and is unique in the document)

– has a STYLE attribute specifying absolute position• needed in NS to modify the region

Page 40: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

40

Something on STYLE• When an HTML tag specifies a style, the

position of the element can be controlled– very useful for layout– for NS to change the text, the position must be absolute

– this creates some awkwardness• the next element is relative, and it turns out this means it will overlap the SPAN region that is being changed

• “fix” this using some BR tags to skip ahead

Page 41: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

41

Changing the SPAN region• NS and IE uses different ways to alter what is

in an HTML region– IE has innerHTML property which when set to a new value displays that HTML in the region

– document.all[id].innerHTML = str;– NS has a document object for each such region• open this document, write to it, and then close it

document[id].document.open();

document[id].document.write(str);

document[id].document.close();

Page 42: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

42

About display()• Checks to see if document.all is defined

– if so, uses IE4 convention of changing innerHTML

– Otherwise assumes NS and uses NS conventions– note, this function will not be called for older browsers, because setInterval is not defined so the onload method does nothing

Page 43: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

43

Accessing the SPAN Region

• A SPAN tag with an ID attribute creates a JavaScript variable that can be used to modify that region of the document– array of objects, one for each HTML tag, with an ID attribute

– accessed using the ID - string with a name– slightly different in NS and IE

• document.all[id] in IE• document[id] in NS• e.g. document.all[“banner”] or document[“banner”]

Page 44: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

44

Highlighting Menus

• Menus whose elements are temporarily highlighted as the mouse moves over them

• One way: use two images for each menu item and change between them using the mouseover and mouseout events– this works in NS and IE version 4 or later

• Second way: use STYLE attributes to dynamically change color, but this is harder to get working on both browsers

Page 45: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

45

Image Object

• Each image in an HTML document has an associated JavaScript object– the properties of the object include

• width and height in pixels• src, URL of the image file, changes image when set• complete, true after images finishes loading

– can refer to object by NAME attribute of HTML IMG tag, or via built-in array of images

• document.images.name• document.images[index] where index is either a

number or a string containing the name of the image

Page 46: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

46

More on Image Object• An image object is created automatically

for each IMG tag in a document– if there is no name attribute, then one cannot

refer to it by name in JavaScript

• An image object can also be created in JavaScriptvar myImage = new Image();– this can be used to load images into a

document that are not visible in the displayed document

– pre-fetching to make images appear immediately

Page 47: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

47

An Image Rollover• Image rollover is the effect used to change

between two images when the mouse moves over it– the images must be the same size– for the changes to be immediate, images must

be pre-fetched

• Generally used in highlighting menus, can be used wherever you want an image to change when the mouse moves over it

• try http://www.ruleweb.com/dhtml/index.html

Page 48: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

48

Rollover Example<HTML><HEAD><TITLE>Image rollover</TITLE><SCRIPT language=javascript>function highlightdocs() {

if (document.images) {document.images[“docs”].src = docsOn.src;}}

function unhighlightdocs() {if (document.images) {

document.images[“docs”].src= docsOff.src;}}if (document.images) {

docsOn = new Image();docsOn.src = “images/docs_on.gif”;docsOff = new Image();docsOff.src = “images/docs_off.gif”;}

</SCRIPT></HEAD><BODY><P><A HREF=“documents.html” onMouseOver=“highlightdocs()”

onMouseOut=“unhighlightdocs()”><IMG SRC=“images/docs_off.gif: height=25 width=25 name=docs

border=0 alt=documents></A></P></BODY></HTML>

Page 49: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

49

Observe in the BODY• The BODY creates an anchor with an

image inside– there are mouse event handlers– image tag sets height, width, no border, alt

text and name– the name is used to refer to the image in

javaScript, document.images[“docs”]

• the HEAD defines two functions– only runs if browser supports image object– changes image by setting its src property to

that of another, pre-fetched image called docs_on.gif

Page 50: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

50

More on the HEAD• Highlighting requires two images

– the image is created, then set is src property which loads the image

– the names docsOn and docsOff are only used inside the functions, so it is OK to define them after• not used until the event handlers are

activated by the mouse moving over the image

Page 51: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

51

Generalizing to Multiple Images• Suppose we want a general

highlight/unhighlight functions for any image in a document

• define two arrays onImages and offImages– store pre-fetched images in these

arrays, according to the same name as used for the image in the HTML

– in general arrays can be indexed by strings as well as numbers

Page 52: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

52

Pre-fetching Required ImagesIf (document.images) {

var onImages = new Array;var offimages = new Array;onImages[“docs”] = new Image();onImages[“docs”].src = “images/docs_on.gif”;offImages[“docs”] = new Image();offImages[“docs”].src = “images/docs_off.gif”;onImages[“tech”] = new Image();onImages[“tech”].src = “images/tech_on.gif”;offImages[“tech”] = new Image();offImages[“tech”].src = “images/tech_off.gif”;

…}

Page 53: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

53

General Highlighting Functions• Name each image in the HTML document

with the same name used in the pre-fetch arrays, onImages and offImages– e.g. the name “docs” was used for the

images, so use the same name in the HTML– then one can highlight by simply setting the

src property of an element in document.images to the src property of that element in onImages

<IMG SRC=“images/docs_off.gif” height=25 width=25 name=docs border=0 alt=documents>

Page 54: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

54

Code for General Highlighting

function highlight(imgName) {if (document.images) {

document.images[imgName].src = onImages[imgName].src;}

}function unhighlight(imgName) {

if (document.images) {document.images[imgName].src =

offImages[imgName].src;}}

Page 55: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

55

Summary• How to write JavaScript that works across

browsers– checking that the browser supports a given

feature such as document.images, before using it

– avoid annoying JavaScript errors that occur when viewing in one browser or the other

• the built-in image object in JavaScript– accessing via name or array of images– created automatically for each IMG tag in the

HTML– can also be created using new Image(); in

JavaScript

Page 56: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

56

But Pre-fetching Repeats Code• Each image to be highlighted requires creating two

images and setting their src properties• Repeated code is an indication of where to use

subroutines• Alternate strategy: create a global array with the

names of all the images that will be used– must be the same as the names in IMG tags– this code requires images stored on the server to have file

names based on these names– specify a path and extensionpath + name + “_on.” + ext(note+appends)so path = “images/”, name=“docs”, ext=“gif” then file must

be in relative location “images/docs_on.gif”

• loop over the elements in this name array, creating and loading the images

Page 57: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

57

Pre-Fetching Functionfunction prefetch(path, extension) {

var imageName, i;if (document.images) {

for ( i = 0; i < imageNames.length; i++) {imageName = imageNames[i];onImages[imageName] = new Image()onImages[imageName].src = path +

imageName + “_on.” + extension;offImages[imageName] = new Image();offImages[imageName].src = path +

imageName + “_off.” + extension;}

}}

Page 58: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

58

Remainder of set-upvar imageNames = new Array(“docs”,

“tech”, “banner1”, “banner2”);if (document.images) {

var onImages = new Array();var offImages = new Array();prefetch(“images/”, “gif”);

}There are four highlighting images in array

Page 59: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

59

Body of Four Images<BODY><P><A HREF=“documents.html”

onMouseOver=highlight(‘docs’) onMouseOut=unhighlight(‘docs’)><img src=images/docs_off.gif name=docs border=0 alt=documents width=25 height=25></A><BR><A HREF=“technology.html” onMouseOver=highlight(‘tech’) onMouseOut=unhighlight(‘tech’)><img src=images/tech_off.gif name=tech border=0 alt=technology width=25 height=25></A><BR>

<A HREF=“members.html” onMouseOver=highlight(‘banner1’) onMouseOut=unhighlight(‘banner1’)><img src=images/banner1_off.gif name=banner1 border=0 alt=banner1 width=25 height=25></A><BR>

. . . But there is still lots of repeated HTML

Page 60: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

60

Reducing Repeated Code

• Use document.write to produce the required HTML

document.write(‘<A HREF=“’ + hrefs[I] + ‘” onmouseover=“highlight(\”” + imageName + “\’)”’ + ‘ onmouseout=“unhighlight(\”’ + imageName + “\’)”>

<IMG src=“’ + path + imageName + “_off.’ + extension + ‘” name=“’ + imageName + ‘”border=“0”’ + ‘ alt=“ ‘ + altText[I] + ‘”width=“’ + w + ‘” height=“’ + h + ‘”></A></BR>

Page 61: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

61

Some Explanations• Considerdocument.write(‘<A HREF=“’ + hrefs[i] +

‘”’);which produces the HTML<A HREF=“documents.html”• Considerdocument.write(‘onmouseover=‘“highlight

(\’’ + imageName + ‘\’)”’which produces the HTMLonmouseover=“highlight(‘docs’)” where imageName has value “docs”

Page 62: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

62

Function for Creating the MenuFunction createHighlightMenu(path, extension, w, h) {

var imageName, I;for (i=0; i <imagesNames.length; i++) {

imageName=imageNames[i];if (document.images) {

onImages[imageName] = new Image();onImages[imageName].src = path +

imageName + “_on.” + extension;

offImages[imageName] = new Image();offImages[imageName].src = path +

imageName + “_off.” + extension;

document.write(‘<A HREF=“’ + hrefs[i] + ‘” onmouseover=“highlight(\’’+imageName + ‘\’)”’ + ‘ onmouseout=“unhighlight(\’ ‘ + imageName + ‘\’)”><IMG src=“’+ path + imageName + ‘_off.’+ extension +’” name=“’+imageName + ‘” border=“0”’ + ‘ alt=“’ + altText[i] + ‘” width=“’ + w + ‘” height=“’ + h + ‘”></A><BR>’); } }

Page 63: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

63

Document Body Using this function

<BODY><P><SCRIPT language=JavaScript>var imageNames = new Array(“docs”, “tech”, banner1”,

“banner2”);var hrefs= new Array(“document.html”, “tech.html”,

“banner1.html”, “banner2.html”);var altText new Array(“Docs”, “Techs”, “banner1”,

“banner2”);if (document.images) {

var onImages = new Array();var offImages = new Array();

}createHighlightMenu(“images/”, “gif”, 25, 25);</SCRIPT></P></BODY></HTML>

Page 64: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

64

JavaScript Object Hierarchyself, window, parent, top

plugins[ ]navigator

mimetypes[ ]frames[ ]

location forms[ ] elements[ ]CurrentWindow history anchors[ ] buttons

checkboxesdocument links[ ] fileUpload

hiddenpackages images[ ]

passwordradio

applets[ ] resetselect

optionsembeds[ ] submit

Java packages textJavaClass objects textarea

Page 65: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

65

JavaScript Built-in Objects and HTML Tags

Object HTML Tag Object HTML Tag

window N/A button <INPUT TYPE=”button”

frame <FRAME> checkbox <INPUT TYPE=”checkbox”

history N/A hidden <INPUT TYPE=”hidden”

location N/A password<INPUT TYPE=”password”

document <BODY> radio <INPUT TYPE=”radio”

form <FORM> reset <INPUT TYPE=”reset”

select <SELECT> submit <INPUT TYPE=”submit”

textarea <TEXTAREA> text <INPUT TYPE=”text”

link <A HREF=””> anchor <A NAME=””>

navigator N/A

Page 66: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

66

Key Objects

• Document object is responsible for all content on a page contains all the user interface elements of a page

• Window object represents a browser window or frame. This is the top-level object for each

document,Location, and History object group. • Frame object • Location object• History object• Form objects can contain user interface

elements for user input• Button objects include a button, submit and

reset buttons

Page 67: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

67

Example Document Object Property Values

Property Value

document.title ”My Home Page"

document.fgColor #000000

document.bgColor #ffffff

location.href "http://www.usc.edu/in.html"

history.length 8

Page 68: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

68

window.open() Method Attribute Examples

•To create a new window that shows only the toolbar and status bar and is resizable

window.open(“newURL”, “New Window”, “toolbar,status,resizable”)

•the height and width defaults are the same as the browser•a new window is positioned in the upper left hand corner of the screen•a call to window.open() returns a value of the new window’s object; this should always be assigned to a variable, e.g.

newWindow = window.open(““,””)

if (newWindow != null) {

newWindow.document.write(“<HTML><HEAD><TITLE>Hi</TITLE></HEAD>”)}

Page 69: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

69

Example<HTML><HEAD><TITLE>Putting Up a Help Window</TITLE>

<SCRIPT LANGUAGE=”JavaScript”>

function displayHelp() {

hWin = window.open(““, “Help”, “height=200,width=400”)

hWin.document.write(“<BODY>A Sample Help Window<BR>”)

hWin.document.write(“Please provide your first and last name<BR>”)

hWin.document.write(“Your Phone number should have no hyphens”)

hWin.document.write(“<FORM><INPUT TYPE=button value=’OK’ onClick=’window.close()’ >”)

hWin.document.write(“</FORM></BODY>”) }

</SCRIPT></HEAD><BODY>

<FORM NAME=”myform” method=”POST”><H2>Here is my Form</H2>

NAME: <INPUT TYPE=”text” name=”name”><BR>

Address: <INPUT TYPE=”text” name=”address”><BR>

Phone: <INPUT TYPE=”text” name=”phone”><BR>

<INPUT TYPE=”submit” VALUE=”Click Here”>

<INPUT TYPE=”button” VALUE=”Help” onClick=”displayHelp()”>

</FORM></BODY></HTML>

Page 70: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

70

Help Window: Browser Output

Page 71: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

71

Example Checking for Empty Fields<HTML><HEAD><TITLE>Elements Array</TITLE>

<SCRIPT LANGUAGE="javaScript">function doit() {

for (i = 0; i <= 3; i++) {if (document.forms[0].elements[i].value == "") {

alert("Please fill out all fields.")document.forms[0].elements[i].focus()break } } }

</SCRIPT></HEAD><BODY> <FORM METHOD="POST">Enter your first name: <INPUT TYPE="text" NAME="firstname"><P>Enter your last name: <INPUT TYPE="text” NAME="lastname"><P><INPUT TYPE="radio" NAME="gender">Male<INPUT TYPE="radio" NAME="gender">Female<P><INPUT TYPE="checkbox" NAME="retired">I am retired<br><INPUT TYPE="button" NAME="act" VALUE="Verify” onClick="doit()"></FORM></BODY></HTML>

Page 72: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

72

Checking for Empty Fields: Browser Output

Page 73: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

73

<HTML><HEAD><TITLE>Checking Elements in a Form</TITLE>

<SCRIPT LANGUAGE=”JavaScript”>

function checkFields() {

var size = document.myform.elements.length

var Flag = true

for (var i = 0; i < size; i++) {

if ((document.myform.element[i].value == null ||

document.myform.element[i].value == ““) &&

(typeof document.myform.element[i].value != ‘submit’ ||

typeof document.myform.element[i].value != ‘reset’)

{ Flag=true; alert(“The “ + document.myform.elements[i].name + “field is blank. Please enter a value.”); break }//endif

} //end of for

return Flag }

</SCRIPT></HEAD><BODY>

Page 74: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

74

<FORM NAME=”myform” method=”POST” onSubmit=”return checkFields()”>

<H2>Here is my Form</H2>

Name: <INPUT TYPE=”text” name=”name”><BR>

Address: <INPUT TYPE=”text” name=”address”>< BR>

Phone: <INPUT TYPE=”text” name=”phone”>< BR>

<INPUT TYPE=”submit” VALUE=”Click Here”>< BR>

</FORM></BODY></HTML>

Page 75: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

75

Browser Output

Page 76: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

76

Multiple Selection Example

<HTML><HEAD><TITLE>Using Multiple Selection Lists</TITLE><SCRIPT LANGUAGE="JavaScript">function displaySelectionValues(objectName) { var ans = ""

for (var i = 0; i < objectName.length; i++) {if(objectName.options[i].selected) {

ans += objectName.options[i].text + "<BR>" } }myWin = window.open("", "Selections", "height=200,width=400")myWin.document.write("you picked these teams<BR>")myWin.document.write(ans) }

</SCRIPT></HEAD><BODY><FORM NAME="myform" method="POST"><SELECT NAME="teams" size=3 multiple><OPTION value="dodgers">Dodgers<OPTION value="yankees">Yankees<OPTION value="angels">Angels </SELECT><BR><INPUT TYPE="button" value="Show Selected Items" onClick="displaySelectionValues(this.form.teams)"></FORM></BODY></HTML>

Page 77: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

77

Multiple Selection Lists: Browser Output

Page 78: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

78

Working with the Date Object

getDate() returns date within month (1-31)

getDay() returns day within week (0-6)

getHours() returns hour within day (0-23)

getMinutes() returns minutes within hour (0-59)

getMonth() returns month within year (0-11)

getSeconds() getTime()

getYear() getTimeZoneOffSet()

setDate(arg) sets date within month (1-31)

setHours(arg) sets hour within day (0-23)

setMinutes(arg)sets minutes within hour (0-59)

setMonth(arg) sets month within year (0-11)

setSeconds() setTime() setYear()

Objects haveget and setfunctions

Page 79: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

79

<HTML><HEAD><TITLE>Using the Date Object </TITLE></HEAD>

<BODY>

The Date object has methods: getMonth(), getDay(), getYear()<br>

<SCRIPT LANGUAGE=”JavaScript”>

update = new Date(document.lastModified)

theMonth = update.getMonth() + 1

theDay = update.getDay()

the Year = update.getYear()

document.writeln(“<I>Last updated:” + theMonth + “/” + theDay + “/” + theYear + “</I>”)

</SCRIPT>

</BODY></HTML>

Page 80: 1 JavaScript csc667/867 Spring 2005 Ilmi Yoon. 2 Outline Basics of JavaScript, Some simple examples Basics of the language variables, types, arrays, objects,

80

Date Object: Browser Output