You are on page 1of 85

JavaScript

Interpreted language Code can be included in an HTML file


Typically, downloaded as part of .html file Interpreted by browser Browser dependencies

Table 1.1 JavaScript compared to Java


JavaScript Interpreted (not compiled) by client. Java Compiled bytecodes downloaded from server, executed on client.

Object-based. No distinction between types of objects. Inheritance is through the prototype mechanism and properties and methods can be added to any object dynamically.
Code integrated with, and embedded in, HTML. Variable data types not declared (loose typing).

Object-oriented. Objects are divided into classes and instances with all inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically.
Applets distinct from HTML (accessed from HTML pages). Variable data types must be declared (strong typing).

Dynamic binding. Object references checked at runtime.


Cannot automatically write to hard disk.

Static binding. Object references must exist at compile-time.


Cannot automatically write to hard disk (in Java Applets).
2

From http://developer.netscape.com/docs/manuals/communicator/jsguide4/index.htm

JavaScript: Resources
Netscape JavaScript reference
http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/

Microsoft JScript Reference (IE)


http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsoriJScript.asp

ECMAScript
http://www.ecma-international.org/publications/standards/Ecma-262.htm

Online books
JavaScript: The Definitive Guide, 4th Edition
http://proquest.safaribooksonline.com/0596000480

JavaScript Application Cookbook


http://proquest.safaribooksonline.com/1565925777

Tutorials
http://www.w3schools.com/js/
3

Debugging
Debugger
Mozilla based browsers (e.g., Netscape) In Netscape: Tools -> Web Development -> JavaScript debugger

Firefox, Tools -> JavaScript Console menu will let you see JavaScript errors In IE5 on MacOS/X, change a preferences setting to see the JavaScript errors displayed.

Overview
Methods of including JavaScript
<script src=>, <script>, events, <a href=>

Language syntax
Variables, persistence, arrays, references to objects, classes, variable scope, control structures, functions

Browser objects
But see DOM (Domain Object Model)

Image objects Dynamic HTML


How to generate HTML code that uses variables and/or conditions from JavaScript

Browser detection
5

Some Uses of JavaScript


Adds full programming language features to HTML documents
E.g., variables, objects, iteration, functions

Output from Javascript program can be displayed to user (e.g., alert boxes) Dynamic creation of HTML & CSS code
Output from JavaScript can also be sent to browser document for interpretation

Access to Domain Object Model (DOM)


Program structured representation of HTML document E.g., access a tag of document by ID
6

JavaScript in HTML documents


<script> </script> tag
Place a block of scripting code into an HTML document This element (i.e., tag) may appear any number of times in an HTML document (e.g., in the HEAD or BODY) Script is executed when that portion of document is interpreted by the browser
7

SCRIPT Tag and Alert box


<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/alert.html</title> <script> alert('Hello world!') </script> </html>

SCRIPT Tag: Optional Attributes


SRC attribute
Name of a file containing JavaScript program code Scripting code between <SCRIPT> and </SCRIPT> tag is ignored when you use this

LANGUAGE attribute
Specifies scripting language & possibly version Default language is JavaScript
Other possibilities include:
VBScript, ECMAScript, C#, jscript, php

E.g.,
<SCRIPT LANGUAGE="JavaScript"> </SCRIPT>
9

Alert Box Using SRC Attribute


<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/src-attribute.html</title>

<script language="JavaScript" src="alert.js"> </script> </html>


alert.js contains: alert('Hello world!')
10

Comments in JavaScript
<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/comment.html</title> <script> // a single line comment /* a multiline comment */ <!-- this is also a single line comment // the code on the next line is the only 'working' JavaScript in the example alert('done with comment example') --> // curiously, this ending comment is needed in IE 5 </script> </html>
11

Technical Detail: Hiding Scripts from Older Browsers


<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/script-hiding.html</title>
<script> <!-- hide script from older browsers // browsers typically ignore tags they don't understand // older browsers will not see this comment // nor will they see the next line of JavaScript code alert('done with script hiding example') // --> </script> </html>

12

JavaScript in Attributes
Some HTML tag attributes expect the attribute value to be a script
Event attributes href

13

Event Attributes
Events include
onfocus, onblur onclick, ondblclick onmousedown, onmouseup, onmouseover, onmousemove, onmouseout onkeypress, onkeydown, onkeyup

Most HTML tags can be coded with event attributes When an event happens, a script can be invoked (e.g., Javascript)
14

Example
<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/button.html</title>

<img src="tiny_pw5.gif" onClick="alert('you clicked the button')">


<!-- Notice the use of single quotes within double quotes. By putting the script code for onClick within double quotes, single quotes can be used for the string parameter that is passed to the alert function. --> </html>

15

<a> tag href JavaScript


href = javascript:<javascript-code>
Execute arbitrary JavaScript code when user clicks on link

<html> <head> <title>www.cprince.com/courses/cs3121/media/JavaScript/ahref.html</title> </head> <body>

<a href="javascript:alert('Clicked!')">Click me</a>


</body> </html>
16

Technical detail
<html> <title>www.cprince.com/courses/cs3121/media/JavaScript-URL.html</title> <a href="javascript:alert('Hello world!')"> This should not cause navigation </a> <p></p> <a href="javascript:returnString('<html> Hello world! </html>')"> If if the last JavaScript statement that is executed in the "javascript:" URL has a string value, some browsers (e.g., Opera 6.03 and Netscape 7.1) will interpret that string value as the contents of web page and try to render it. </a> <p></p> <a href="javascript:void 0"> This should not cause navigation; explicitly doesn't have a string value </a> <p></p> <a href="javascript:void(0)"> Another way to code the same thing </a> <script> function returnString(s) { return s; } </script> </html>

17

Keywords & Identifiers


Keywords
JavaScript is case sensitive E.g., null is not the same as Null, NULL, or any other variant. Identifiers (E.g., for variables)
First character
Letter A-Z or a-z (upper case or lower case) Underscore (_) Dollar sign ($)

Next characters
Letters, digits, underscores, $

Cannot be the same as keywords (reserved words)


18

Variables in JavaScript
Variables
Data types include: Strings, integers, floats Variables are implicitly typed

Syntax
var variableName // var is a reserved word var variableName = value If within a function, variable is local to function; otherwise, variable has global scope (see ECMAScript reference) Omitting var-- creates a global variable anywhere

Example
var PI = 3.14 var myStr = this is a string followed by the value of PI + PI // this demonstrates string concatenation in JavaScript
19

Dynamic Typing
Not only implicit typing, but dynamic typing
i.e., The data type of a variable can be changed

E.g.,
var car = ford // type of car variable is string car = 25 // now, type is changed to integer car = 3.14 // type changed to float

20

Object Values
Numbers: integer and real
E.g., 42 or 3.14159 or -3.1E12 026 (begins with 0 octal); 0xff (begins with 0x hex)

Logical (Boolean) values


true or false

Strings: double quoted & single quoted


"Howdy!" Howdy! Special characters
\n newline \\ - backslash character \ can be used to escape characters, e.g., to insert a quote

null
keyword denoting no value Not the same as the empty string (), nor fully same as undefined
21

Variable Example
<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/variable.html</title>

<script> var PI = 3.14; myStr = "this is value of pi: " // semi-colon is optional with one statement alert(PI); alert(myStr) // output value of a in an alert box // then value of b in a second alert box alert(myStr + PI) // string concatenation

</script> </html>

Generates series of three alert boxes


22

JavaScript Variables Persist Past Initial SCRIPT Section


<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/variable-persistence.html</title>

<script> var PI = 3.14; myStr = "this is value of pi: " </script> <!-- Variables PI and myStr persist to next script section --> <script> alert(myStr + PI) </script> <!-- and they persist to HTML code following in the document --> <img src="tiny_pw5.gif" onClick="alert(myStr + PI)" title="click here"> </html>
23

Variable Scope & Persistence


Variables do not persist to a linked web page
<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/variable-persistence2.html</title>

<script>

var PI = 3.14; myStr = "this is value of pi: "


</script> <! Test if variables PI and myStr persist to a linked file -->

<a href="variable-link.html">Click here</a>


</html>

When this link is clicked, it causes an error; PI and myStr cannot be accessed in the linked file

variable-link.html
<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/variable-link.html</title>

<script>
// try to access PI and myStr. Do they have values in this linked html document?

alert(PI) alert(myStr) </script> </html> 24

Arrays
Creating
var a = new Array(); // using array constructor var b = [1.2, JavaScript, false]; // literal array // note that arrays can have values of // heterogeneous types var c = new Array(1.2, JavaScript, false); // initializer can be given as parameters

Indexing
Ranges from element 0, to element N-1 e.g., alert(b[0])

Elements not defined or initialized are undefined

25

Array Example
<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/arrays-alert.html</title> <script> var a = new Array(); a[10] = "my name is Sue"; var b = [1.2, "JavaScript", false]; b[10] = "my name is not Sue"; var result = "" result += 'a[10]= ' + a[10] + '\n' result += 'b[10]= ' + b[10] + '\n' var i=0; result += 'a[' + i + ']= ' + a[i] + '\n' result += 'b[' + i + ']= ' + b[i] + '\n' i=1 result += 'a[' + i + ']= ' + a[i] + '\n' result += 'b[' + i + ']= ' + b[i] + '\n' i=2 result += 'a[' + i + ']= ' + a[i] + '\n' result += 'b[' + i + ']= ' + b[i] + '\n' alert(result) </script> </html>

Output?
26

More Array Details


Data members
length data member gives current number of elements in the array

Methods include
concat, join pop, push reverse, shift, unshift slice splice: Insert, delete or replace array elements toString
27

Primitive Types & Reference Types


Primitive types
represented by value Includes: numbers, booleans (true, false)

Objects, string & arrays


Represented by reference
Like a pointer Different variables can reference the same data object

Similar to Java
28

Example
var x = [1, 2, 3]; // x is an array // (is a reference type) x

[1, 2, 3]

var y = x; // y references the contents of x

x
y

[1, 2, 3]

// change what x and y refer to x[0] = 99;

x
y

[99, 2, 3]

29

Example
<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/reference-types-alert.html</title> <script> // example modified from Flanagan (1998) var result = "" // "primitive" data example var a = 3.14; var b = a; // b is now a copy of the value of a a = 4; result += 'a= ' + a + '\n' result += 'b= ' + b + '\n' // "reference" data example var x = [1, 2, 3]; var y = x; // y references the contents of x x[0] = 99; // outputting an array by its name outputs // all elements of the array result += 'x= ' + x + '\n' result += 'y= ' + y + '\n' alert(result) </script> </html>

QuickTime and a TIFF (LZW) decomp resso r are need ed to see this picture.

30

Defining & Calling Functions


Defining functions: syntax
function function-name (parameter1, parameter2,) { function-statements return [value] // optional } Parameter list
Comma separated list, in parentheses Names only; No data types for parameters

Calling functions
Give function name and give actual parameters in parenthesis Function with return result
Assign or ignore result
31

Example Functions
<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/functions.html</title> <script> function square(number) { return number * number }

function myAlert(message) { alert(message) }


square(3) // a little useless! var value = square(3) alert("three squared is: " + value) alert("three squared still is: " + square(3)) myAlert("hi there!") </script> </html>

32

Control Structures: if-else


if (expression)
statement

[ else statement2 ] if (expression) statement else if (expression2) statement2


33

Control Structures: switch


switch (n) { case: // statements break default: break }
34

Control Structures: Iteration


while (expression)
Statement

do statement while (expression) for (var initialize; test; increment) statement for (var x in y) statement // iterate over all properties x of an object y, or // all defined indices x of an array y

35

Control Structure Example


<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/control.html</title> <script> var a = 1 var b = 2 var c = "hello" // this is a string literal; also have String objects. var d = "hell" + "o" if (c == d) { // test for string equality; doesn't compare references alert('c and d are equal') } while (a != b) { a++ } alert('done while loop')

switch (a) { case 1: alert('case 1'); break case 2: alert('case 2'); break default: alert('default'); break } </script> </html>

36

Example
Write a JavaScript function that accepts an array of numbers as a parameter, sums all of the numbers in the array, and returns that sum as the result of calling the function Also, give all necessary HTML code to run the example in a browser

37

Solution
<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/function-example.html</title>

<script>
function sumArray(numArray) { var sum = 0; for (var x=0; x < numArray.length; x++) { sum += numArray[x] } return sum; }

var arrExample = [9, 8, 3, 10]; var theSum = sumArray(arrExample); alert(theSum);


</script> </html>
38

Alternative Solution
<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/function-example2.html</title>

<script>

function sumArray(numArray) { var sum = 0; // Use other for iteration syntax // x takes on the values of the defined array indices for (var x in numArray) { sum += numArray[x] }
return sum; } var arrExample = [9, 8, 3, 10]; arrExample[10] = 3; var theSum = sumArray(arrExample); alert(theSum);

</script>
</html>

39

Variable Scope: Local vs. Global


Omitting a var declaration in an assignment creates a global variable
E.g., x = 10 // if x has not appeared before, x is global

Local variables (with var) in JavaScript can only be accessed in the immediate scope in which they were declared Can create globals anywhere
Inside of functions Outside of functions

40

Scope Example 1
<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/variable-scope1.html</title> <script> x = "assigned global"; var y = "declared global"; var result; function test() { result = "" result += "Test function: x= " + x + "\n" result += "Test function: y= " + y + "\n" alert(result) } test()
result = "" result += "After function: x= " + x + "\n" result += "After function: y= " + y + "\n"

QuickTime and a TIFF (LZW) decompressor are neede d to see this picture.

alert(result) </script> </html>

QuickTime an d a TIFF (LZW) decomp ressor are need ed to see this p icture .

41

Scope Example 2
<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/variable-scope2.html</title> <script> x = "assigned global"; var y = "declared global"; var result;

function test() { var y = "declared local"; z = "assigned in function";


result = ""; result += "Test function: x= " + x + "\n" result += "Test function: y= " + y + "\n" result += "Test function: z= " + z + "\n" alert(result) } test() result = "" result += "After function: x= " + x + "\n" result += "After function: y= " + y + "\n" result += "After function: z= " + z + "\n" alert(result) </script> </html>
QuickTime and a TIFF (LZW) decomp resso r are neede d to see this picture.

QuickTime and a TIFF (LZW) deco mpressor are neede d to se e this picture.

Notice these!

42

<html>

Scope Example 3
<title>www.cprince.com/courses/cs3121/media/JavaScript/variable-scope3.html</title> <script> x = "assigned global"; var y = "declared global"; var result; function test() { z = "assigned in function"; result = ""; result += "Test function: x= " + x + "\n" result += "Test function: y= " + y + "\n" result += "Test function: z= " + z + "\n" var y = "declared local"; alert(result) } test()
QuickTime and a TIFF (LZW) deco mpressor are neede d to se e this picture.

result = "" result += "After function: x= " + x + "\n" result += "After function: y= " + y + "\n" result += "After function: z= " + z + "\n"
alert(result)
QuickTime and a TIFF (LZW) decomp resso r are neede d to see this picture.

43

</script>

Variable Declaration Scope


The variable can have effect before its declaration is reached in execution of the program code! A var declared variable, in a function will shadow another variable with the same name even before its reached in the execution of the function
44

JavaScript Objects, & Properties


Object a structured variable
Objects have associated properties Properties can be data or functions Created with constructors or with syntax:
new Object()

Property syntax:
variableName.propertyName variableName[propertyNameVariableOrString]

Example
To create Object named myCar, with three propertiesmake, model, and year, use the following statements: var myCar = new Object() myCar.make = "Ford" myCar.model = "Mustang" 45 myCar.year = 67

Full Example: Using dot notation


<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/objects.html</title>

<script> // assumes an object with data properties: .make, .model, .year // output's those in an alert box. function alertCar(aCar) { alert(aCar.make + ' ' + aCar.model + ' ' + aCar.year) } var myCar = new Object() myCar.make = "Ford" myCar.model = "Mustang" myCar.year = 67; alertCar(myCar) </script> </html>
46

Full Example: Using [] notation


<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/objects2.html</title>

<script> // Show another way to access components of objects. This time, // with string component names. function alertCar(aCar) { alert(aCar["make"] + ' ' + aCar["model"] + ' ' + aCar["year"]) }

var myCar = new Object() // now use variables with string values to access object components var prop1 = "make"; var prop2 = "model"; var prop3 = "year"; myCar[prop1] = "Ford" myCar[prop2] = "Mustang" myCar[prop3] = 67;
alertCar(myCar) </script>
QuickTime an d a TIFF (LZW) decomp ressor are need ed to see this p icture .

</html>

47

Using Object Constructors to Create Objects


Object constructor:
Name of function is the object type you are creating Use this to refer to the object being created function car(make, model, year) { this.make = make this.model = model this.year = year }

Use new with name of constructor to create new Object


E.g., create a car object

myCar = new car("Eagle", "Talon TSi", 1993)

48

Example: Using Constructor


<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/constructor.html</title>

<script> function car(make, model, year) { this.make = make this.model = model this.year = year } function alertCar(aCar) { alert(aCar.make + ' ' + aCar.model + ' ' + aCar.year) } // Now, create an object called myCar: myCar = new car("Eagle", "Talon TSi", 1993) alertCar(myCar) </script> </html>
49

Defining methods

Methods

Properties can be assigned functions in constructor A function name assigned to a property acts as a reference to the function Can be subsequently used to call the function Example:
function printCar() { alert(this.make + ' ' + this.model + ' ' + this.year) } function car(make, model, year) { this.make = make this.model = model this.year = year this.print = printCar // define a method property }

Method invocation myCar = new car("Eagle", "Talon TSi", 1993) myCar.print()

50

<html>

Example

<title>www.cprince.com/courses/cs3121/media/JavaScript/object-method.html</title>

<script> // alertCar as an object method function printCar() { // use this to access object properties alert(this.make + ' ' + this.model + ' ' + this.year) } function car(make, model, year) { this.make = make this.model = model this.year = year this.print = printCar // define a method property for the object type }

//Now, create an object called myCar: myCar = new car("Eagle", "Talon TSi", 1993)
myCar.print() // invoke the print method </script> </html>

51

<html>

Example: Nested Method

<title>www.cprince.com/courses/cs3121/media/JavaScript/object-method-nested.html</title>

<script> function car(make, model, year) { // printCar as an object method, nested within the car constructor function printCar() { // use this to access object properties alert(this.make + ' ' + this.model + ' ' + this.year) } this.make = make this.model = model this.year = year this.print = printCar // define a method property for the object type }

//Now, create an object called myCar: myCar = new car("Eagle", "Talon TSi", 1993)
myCar.print() // invoke the print method </script> </html>

52

Iterating Through Object Properties


// iterate through object properties for (var variable in object) statement // variable will successively take on the names // of the object properties. // variable values will be strings.

53

Example
<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/property-iteration.html</title>

<script> function car(make, model, year) { this.make = make this.model = model this.year = year }

//Now, create an object called myCar: myCar = new car("Eagle", "Talon TSi", 1993)
var result = ""; // Iterate through the properties of the object for (var x in myCar) { result += x + ": " + myCar[x] + "\n"; } alert(result) </script>

QuickTime an d a TIFF (LZW) decomp ressor are need ed to see this p icture .

54

</html>

Exercise
Write a JavaScript function that:

1) takes a single parameter, any object, as input; 2) iterates through all properties of the object and outputs the value of the properties using alert.

55

Solution
<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/objects-varproperty2.html</title>

<script src="showAllProperties.js"> </script> <script> var myCar = new Object() myCar.make = "Ford" myCar.model = "Mustang" myCar.year = 67; showAllProperties(myCar) </script>

</html>
// File: showAllProperties.js // output the properties of an object using 'alert' function showAllProperties(anObject) { var result = "Object Properties:\n" for (var propname in anObject) { // remember: object[propertyVariable] lets you // access a property of an object result += propname + ": " + anObject[propname] + "\n" } alert(result) }

56

String Functions
Variable.toString
Provided with objects to enable the object to be output (e.g., using alert); for new classes, define your own toString method

Can be used with some non-object types


E.g., number.toString

Number.toNumber
Convert a string (or other object) to a number (must be applied to a numeric variable, not a constant)

String.indexOf(substring)
Returns the position (0 is leftmost) of the first occurrence of substring within the string; -1 if it does not occur

parseInt(string)
Extract out an integer value, left to right, in string

parseFloat(String)

57

Object toString
<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/toString.html</title> <script> function car(make, model, year) { // return a string reflecting contents of a car object function toString() { return this.make + ' ' + this.model + ' ' + this.year } this.make = make this.model = model this.year = year this.toString = toString }

myCar = new car("Eagle", "Talon TSi", 1993)


alert(myCar) </script> </html>
QuickTime an d a TIFF (LZW) decomp ressor are need ed to see this p icture .

58

<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/string.html</title> <script> var result = ""; var number = 10; var numString = number.toString(); result += numString + '\n'; var floatNum = 10.3; var floatString = floatNum.toString(); result += floatString + '\n'; var testString = "this is a test"; if (testString.indexOf("this") != 0) { alert("Problem with finding 'this'") } if (testString.indexOf("test") == -1) { alert("Problem with finding 'test'") } if (testString.indexOf("notthere") != -1) { alert("Problem with finding 'notthere'") } var fontSizeText = "100pt"; var pointSize = parseInt(fontSizeText); result += pointSize + '\n'; alert(result) </script> </html>

Other String Functions

QuickTime an d a TIFF (LZW) decomp ressor are need ed to see this p icture .

59

Browser Built-in Objects


Browsers have internal built-in objects
Having both data and function properties

window object
Represents a browser window Data properties include:
location: URL of current html document defaultStatus, status: text in status line of browser history: object giving users browsing history navigator: Properties include: appName, platform screen: Properties include: width, height document: Properties include bgColor (background color), fgColor (foreground color), write, all (all tags in document) open(): open a new window close(): close the window moveBy(), moveTo(): move the window resizeBy(), resizeTo(): resize the window scrollBy(), scrollTo(): scroll the window setInterval(), clearInterval() setTimeout(), clearTimeout(): schedule a function to be called alert(), confirm() prompt() prompt for text

Methods include:

60

One Means of Referencing Document Contents


document.images[]
Array of all images rendered using IMG tags

document.links[]
Array of all URL links (A HREF tags) in the document, and <AREA> tags (client-side image maps)

document.anchors[]
A NAME tags

document.applets[]
<APPLET> tag items

document.embed[]
<EMBED> tag items

document.forms[]
<FORM> tag items
61

Another Means of Referencing Document Contents


Some tags with name or id attributes, can be accessed as
window.document.<nameOrId> Or just document.<nameOrId>

Attributes of tag can then be accessed as


document.<nameOrId>.<attribute>

E.g., if an image has an id myImage and a style tag, you can change properties that style in JavaScript with
document.myImage.style.border = solid blue;

The src attribute can be used to change the image 62 itself

Changing Image Attributes - 1


<html> <head> <title>www.cprince.com/courses/cs3121/media/JavaScript/image-access.html </title> </head> <body> <!-- create the tag --> <img src = "meowsie.jpg" id = "theImage" style = "border: solid red"> <!-- Now, use JavaScript code to access the image --> <script> alert("Just wait...") document.theImage.style.border = "solid blue"; document.theImage.src = "tiny_pw5.gif"; </script> </body> </html>

63

More window Object Properties


window.history methods include
back()
take the browser to previous page accessed Same effect as browser back button

forward()
take browser forward if the browser has previously gone back Same effect as browser forward button

location property
Setting this changes the document loaded into the browser window
64

<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/history.html</title> <!-- button to cause a return to the web page we were previously viewing (if any) --> <!-- button type can be submit, reset or button --> <button type="button onClick="window.history.back()"> Back </button> <!-- button to go forward to a previously viewed page (if any) --> <button type="button" onClick="window.history.forward()"> Forward </button> </html>

Example

QuickTime an d a TIFF (LZW) decomp resso r are need ed to see this picture .

65

Changing the location


<html>
<title> www.cprince.com/courses/cs3121/media/JavaScript/location.html </title>

<script> newURL = prompt("Enter new URL (http:// must be prepended):") if (newURL != "") { window.location = newURL } </script> </html>

http:// only needed for Internet web 66 site (not local) document access.

window methods
window.open, window.close, window.focus
Methods of window object in a browser Open returns a reference to the new window that was opened

Enable a new browser window to be opened (and closed); and window to be brought to foreground Parameters for open method
open (URL, windowName[, windowFeatures])

QuickTime and a TIFF (LZW) decompressor are neede d to see this picture.

67 http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

Example
<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/window1.html</title> <script> var myWindow = null; // this will refer to the new window we open </script> <p>This is the main window. </p> <script>
function TestWindow() { myWindow = window.open ("window-to-open.html","mywindow","status=1"); alert("This is from the main window"); myWindow.focus(); myWindow.alert("Please press enter..."); // now you can see that alert is a window method focus(); }

</script>
<a href="javascript:TestWindow()">Click to test window functions </a> <p> <a href="javascript:myWindow.close()">Click here to close the other window </a>

</html>
68

Dynamically Altering the HTML Document: document.write


A method that lets you output to the current browser document Outputting to the document results in an active process of HTML interpretation! So, you can dynamically generate HTML code
69

document.write processing
JavaScript statements using document.write
e.g., document.write(<br> hi!) HTML document window (Browser display)

HTML code (not in JavaScript)

HTML interpretation

e.g., <br> there!

document.write
<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/document-write-first.html</title>

<script> document.write('<br> hi!') </script> <p>this is a paragraph<p> </html>

HTML interpretation

71

document.write Example: Outputting Text


<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/document-write.html</title> <script> document.write('hi there this is an example of some text') document.write(' being written to the output') document.write(' and here is even still more ') document.write(' text in the ') document.write('output') </script> <!-- the above dynamically generated document will be processed as if we had the following OUTSIDE of the script tag:
hi there this is an example of being written to the output and here is even still more some text

text

in the

output --> </html>

72

Exercise
Write a function that takes a single parameter, a string containing a URL, and outputs an anchor tag (A HREF) to the document for that URL E.g., if passed a parameter:
"http://www.ssa.org, it will output this <a href= "http://www.ssa.org">link</a>
73

Solution
<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/document-write-HTML2.html</title>

<script> function outputURL(URL) { document.write('<a href='); document.write(URL); document.write('>link</a>'); } outputURL("http://www.ssa.org") </script>

</html>

74

Using JavaScript Variables


<html>
<!-- www.cprince.com/courses/cs3121/media/JavaScript/variables-in-attributes1a.html -->

<script> // declare some variables myHomePage = 'http://www.cprince.com' </script> <script> document.write('<A href=') document.write('"') document.write(myHomePage) document.write('"') document.write('>Click here!</A>'); </script> </html>

QuickTime and a TIFF (LZW) decompressor are neede d to see this picture.

75

Only one document.write


<html>
<!-- www.cprince.com/courses/cs3121/media/JavaScript/variables-in-attributes1b.html -->

<script> // declare some variables myHomePage = 'http://www.cprince.com' </script> <script>


document.write('<A href=' + '"' + myHomePage + '"' + '>Click here!</A>');

</script> </html>

76

Another Example
<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/variables-in-attributes2.html</title>

<script> // declare some variables barWidth = '50%' // we want our bars to be 50% of the window width </script> <script> // the HR tag creates a horizontal rule across the browser window document.write('<HR WIDTH="' + barWidth + '" ALIGN="LEFT">') </script> </html>
QuickTime and a TIFF (LZW) decomp resso r are need ed to see this picture.

77

document.write
During the document rendering process
E.g., in <script> tags Outputs to the document as it is rendered, along with the HTML tags in the document

After rendering
E.g., As called via event handlers (e.g., onClick from a button) Resets (clears) the document Any prior rendered HTML tags are lost!
78

<html> <head> <title>www.cprince.com/courses/cs3121/media/JavaScript/reset.html</title> </head>

Document Reset

<body> Here is some text. This text will be erased when we click on the button. And, the button too will go away! <p> The rule is: During document rendering, you can use document.write as much as you want. These write statements will be rendered into the document along with the HTML code. After document rendering is completed, use of document.write resets the document contents. </p> <button type="button" onClick="document.write('Yikes!')"> Reset Document </button> </body> 79 </html>

Another Debugging Technique


// file: http://www.cprince.com/courses/cs3121/media/JavaScript/utils.js // Call this to start sending debugging output out to a new browser window function StartDebug() { // Usually a "no no"-- create a new global variable to // refer to our window _debugWindow = window.open("","debugWindow","status=1"); } // Send the debugging output given in the string to our debug window function Debug(s) { _debugWindow.document.write('<br>') _debugWindow.document.write(s) <html> }

<head>

<title>www.cprince.com/courses/cs3121/media/JavaScript/debug.html </title> <script src="utils.js"> </script> <script> StartDebug(); </script> </head>

<body> <script> Debug("Some debugging output") URL = "http://www.cprince.com" </script> <a href="javascript:Debug('Variable value= ' + URL)">Click here </a> </body> </html>

80

Browser Dependencies
It can be useful to detect which browser your JavaScript code is running in To alter what the code (e.g., HTML, CSS, or JavaScript) does based on the particular browser
E.g., deal with browser dependencies

window.navigator
Has information about the current browser Properties include
appName (Netscape or Microsoft Internet Explorer) appVersion userAgent appCodeName (not useful) Platform (operating system) language (e.g., en or fr)

81

<html> <title>www.cprince.com/courses/cs3121/media/JavaScript/browser.html</title> The browser appName is: <SCRIPT> document.write(window.navigator.appName) </SCRIPT> <br>The browser userAgent is: <SCRIPT> document.write(window.navigator.userAgent) </SCRIPT> <br>The browser appCodeName is: <SCRIPT> document.write(window.navigator.appCodeName) </SCRIPT> <br>The browser platform is: <SCRIPT> document.write(window.navigator.platform) </SCRIPT> </html>

82

Safari 2.0.4 (Mac):

Mac Results

The browser appName is: Netscape The browser userAgent is: Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/418.9 (KHTML, like Gecko) Safari/419.3 The browser appCodeName is: Mozilla The browser platform is: MacPPC

IE 5.2 (Mac):
The browser appName is: Microsoft Internet Explorer The browser userAgent is: Mozilla/4.0 (compatible; MSIE 5.23; Mac_PowerPC) The browser appCodeName is: Mozilla The browser platform is: MacPPC

Firefox 1.5.0.7 (Mac):


The browser appName is: Netscape
The browser userAgent is: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8.0.7) Gecko/20060909 Firefox/1.5.0.7

The browser appCodeName is: Mozilla The browser platform is: MacPPC

Netscape 7.1 (Mac):


The browser appName is: Netscape The browser userAgent is: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 The browser appCodeName is: Mozilla 83 The browser platform is: MacPPC

Windows Results
Firefox 1.0.4 (Windows)
The browser appName is: Netscape The browser userAgent is: Mozilla/5.0(Windows; U; WindowsNT 5.1; en-US; rv:1.7.8) Gecko/20050511 Firefox/1.0.4 The browser appCodeName is: Mozill a The browser platform is: Win32

IE 6.0.29 SP2 (Windows)


The browser appName is: Microsoft Internet Explorer The browser userAgent is: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322) The browser appCodeName is: Mozill a The browser platform is: Win32

84

Internet Explorer Detection


// file: http://www.cprince.com/courses/cs3121/media/JavaScript/utils.js // return true if browser is IE; false otherwise. function BrowserIsIE() { if (navigator.appName.indexOf("Microsoft") != -1) { // indexOf method returns the position of the search string within the string // returns -1 only when string not found // navigator.appName == "Microsoft Internet Explorer" for IE // navigator.appName == "Netscape" for other browsers Ive tested return true; } else { return false; <html> } <head> } <title>www.cprince.com/courses/cs3121/media/JavaScript/browser-detect.html </title>
<script src="utils.js"> </script> </head>

<body>
<script> if (BrowserIsIE()) { document.write("This browser is Microsoft Internet Explorer") } else { document.write("This browser is *not* Microsoft Internet Explorer") } </script>

85

</body>
</html>

You might also like