Professional Documents
Culture Documents
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).
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/
ECMAScript
http://www.ecma-international.org/publications/standards/Ecma-262.htm
Online books
JavaScript: The Definitive Guide, 4th Edition
http://proquest.safaribooksonline.com/0596000480
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)
Browser detection
5
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
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
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
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>
15
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
Next characters
Letters, digits, underscores, $
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)
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>
<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
<script>
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?
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])
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
Methods include
concat, join pop, push reverse, shift, unshift slice splice: Insert, delete or replace array elements toString
27
Similar to Java
28
Example
var x = [1, 2, 3]; // x is an array // (is a reference type) x
[1, 2, 3]
x
y
[1, 2, 3]
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
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 }
32
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
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; }
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
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.
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;
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>
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
<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
<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
48
<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 }
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>
<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
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
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 }
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>
QuickTime an d a TIFF (LZW) decomp ressor are need ed to see this p icture .
59
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
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
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;
63
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
<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
document.write processing
JavaScript statements using document.write
e.g., document.write(<br> hi!) HTML document window (Browser display)
HTML interpretation
document.write
<html>
<title>www.cprince.com/courses/cs3121/media/JavaScript/document-write-first.html</title>
HTML interpretation
71
text
in the
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>
</html>
74
<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
</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
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>
<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
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
The browser appCodeName is: Mozilla 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
84
<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>