-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
1/84
1 2001-2002 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
JavaScriptAdding Dynamic Content
to Web Pages
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
2/84
JavaScript2 www.corewebprogramming.com
Agenda
Generating HTML Dynamically
Monitoring User Events
Basic JavaScript Syntax
Applications
Using JavaScript to customize Web pagesUsing JavaScript to make pages more dynamic
Using JavaScript to validate CGI forms
Using JavaScript to manipulate HTTP cookiesUsing JavaScript to interact with and control frames
Controlling applets and calling Java from JavaScript
Accessing JavaScript from Java
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
3/84
JavaScript3 www.corewebprogramming.com
Generating HTML Dynamically
IdeaScript is interpreted as page is loaded, and uses
document.write or document.writeln to insertHTML at the location the script occurs
Template...
Regular HTML
More Regular HTML
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
4/84
JavaScript4 www.corewebprogramming.com
A Simple Script
First JavaScript Page
First JavaScript Page
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
5/84JavaScript5 www.corewebprogramming.com
Simple Script, Result
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
6/84JavaScript6 www.corewebprogramming.com
Extracting Document Info with
JavaScript, Example
Extracting Document Info with JavaScriptExtracting Document Info with JavaScript
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
7/84JavaScript7 www.corewebprogramming.com
Extracting Document Info with
JavaScript, Example, cont....document.writeln("Document Info:\n" +"\n" +
" URL: " + document.location + "\n" +" Modification Date: " + "\n" +
document.lastModified + "\n" +" Title: " + document.title + "\n" +" Referring page: " + referringPage() + "\n" +
"");document.writeln("Browser Info:" + "\n" +"" + "\n" +" Name: " + navigator.appName + "\n" +
" Version: " + navigator.appVersion + "\n" +"");
// -->
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
8/84JavaScript8 www.corewebprogramming.com
Extracting Document Info with
JavaScript, Result
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
9/84JavaScript9 www.corewebprogramming.com
Extracting Document Info with
JavaScript, Result
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
10/84JavaScript10 www.corewebprogramming.com
Multi-Browser Compatibility
1. Use Language Attribute
...
Note: Dont include that attribute TYPE="text/javascript"
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
11/84JavaScript11 www.corewebprogramming.com
Multi-Browser Compatibility,
cont.2. Use Vendor/Version Info navigator.appName
navigator.appVersion
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
12/84JavaScript12 www.corewebprogramming.com
Monitoring User Events
Use Various onXxx AttributesonClick
onLoadonMouseOver
onFocus
etc.
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
13/84JavaScript13 www.corewebprogramming.com
User Events, Example
Simple JavaScript Button
Simple JavaScript Button
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
14/84
JavaScript14 www.corewebprogramming.com
User Events, Result
S S
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
15/84
JavaScript15 www.corewebprogramming.com
JavaScript Syntax: Dynamic
Typing IdeaLike Lisp, values are typed, not variables
A value is only checked for proper type when it isoperated upon
Example
var x = 5; // int
x = 5.5; // float
x = "five point five"; // String
J S i t S t F ti
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
16/84
JavaScript16 www.corewebprogramming.com
JavaScript Syntax: Function
Declarations1. Declaration Syntax Functions are declared using the function reserved word The return value is not declared, nor are the types of the
arguments
Examples:
function square(x) {return(x * x);
}
function factorial(n) {
if (n
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
17/84
JavaScript17 www.corewebprogramming.com
JavaScript Syntax: Function
Declarations, cont.2. First Class Functions Functions can be passed and assigned to variables
Example
var fun = Math.sin;
alert("sin(pi/2)=" + fun(Math.PI/2));
J S i t S t Obj t d
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
18/84
JavaScript18 www.corewebprogramming.com
JavaScript Syntax: Objects and
Classes1. Fields Can Be Added On-the-Fly Adding a new property (field) is a simple matter of
assigning a value to one If the field doesnt already exist when you try to assign
to it, JavaScript will create it automatically.
For instance:
var test = new Object();
test.field1 = "Value 1"; // Create field1 property
test.field2 = 7; // Create field2 property
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
19/84
J S i t S t Obj t d
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
20/84
JavaScript20 www.corewebprogramming.com
JavaScript Syntax: Objects and
Classes, cont.3. The "for/in" Statement Iterates OverProperties
JavaScript, unlike Java or C++, has a construct that letsyou easily retrieve all of the fields of an object
The basic format is as follows:
for(fieldName in object) {
doSomethingWith(fieldName);
}
Also, given a field name, you can access the field viaobject["field"] as well as via object.field
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
21/84
JavaScript21 www.corewebprogramming.com
Field Iteration, Example
For/In Loops
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
22/84
JavaScript22 www.corewebprogramming.com
Field Iteration, Example
...For/In Loops
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
23/84
JavaScript23 www.corewebprogramming.com
Field Iteration, Result
The for/in statement iterates over
object properties
JavaScript Syntax: Objects and
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
24/84
JavaScript24 www.corewebprogramming.com
JavaScript Syntax: Objects andClasses, cont.
4. A Constructor is Just a Function thatAssigns to this
JavaScript does not have an exact equivalent to Javasclass definition The closest you get is when you define a function that
assigns values to properties in the this reference
Calling this function using newbinds this to a newObject
For example, following is a simple constructor for aShip class
function Ship(x, y, speed, direction) {this.x = x;this.y = y;this.speed = speed;this.direction = direction;
}
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
25/84
JavaScript25 www.corewebprogramming.com
Constructor, Example
var ship1 =
new Ship(0, 0, 1, 90);
makeObjectTable("ship1", ship1);
JavaScript Syntax: Objects and
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
26/84
JavaScript26 www.corewebprogramming.com
JavaScript Syntax: Objects andClasses, cont.
5. Methods Are Function-Valued Properties No special syntax for defining methods of objects
Instead, you simply assign a function to a property
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
27/84
JavaScript27 www.corewebprogramming.com
Class Methods, Example
Consider a version of the Ship class thatincludes amove method
function degreesToRadians(degrees) {return(degrees * Math.PI / 180.0);
}
function move() {
var angle = degreesToRadians(this.direction);this.x = this.x + this.speed * Math.cos(angle);this.y = this.y + this.speed * Math.sin(angle);
}
function Ship(x, y, speed, direction) {this.x = x;this.y = y;this.speed = speed;
this.direction = direction;this.move = move;}
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
28/84
JavaScript28 www.corewebprogramming.com
Class Methods, Result
var ship1 = new Ship(0, 0, 1, 90);
makeObjectTable("ship1 (originally)", ship1);
ship1.move();
makeObjectTable("ship1 (after move)", ship1);
JavaScript Syntax: Objects and
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
29/84
JavaScript29 www.corewebprogramming.com
JavaScript Syntax: Objects andClasses, cont.
5. Arrays For the most part, you can use arrays in JavaScript a lot like Java
arrays.
Here are a few examples:var squares = new Array(5);
for(var i=0; i
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
30/84
JavaScript30 www.corewebprogramming.com
Array, Example
var arrayObj = new Object();
arrayObj[0] = "Index zero";
arrayObj[10] = "Index ten";
arrayObj.field1 = "Field One";arrayObj["field2"] = "Field Two";
makeObjectTable("arrayObj",
arrayObj);
Application: Adjusting to the
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
31/84
JavaScript31 www.corewebprogramming.com
Application: Adjusting to theBrowser Window Size
Netscape 4.0 introduced thewindow.innerWidth and
window.innerHeight propertiesLets you determine the usable size of the current browserwindow
Determining Browser Size
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
32/84
JavaScript32 www.corewebprogramming.com
Determining Browser Size,Example
Strawberries
Determining Browser Size,
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
33/84
JavaScript33 www.corewebprogramming.com
Determining Browser Size,Example, cont.
...
Strawberries are my favorite garden crop; a fresh ...
Determining Browser Size,
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
34/84
JavaScript34 www.corewebprogramming.com
Determining Browser Size,Results
Application: Using JavaScript
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
35/84
JavaScript35 www.corewebprogramming.com
Application: Using JavaScriptto Make Pages Dynamic
Modifying Images Dynamically The document.imagesproperty contains an array of
Image objects corresponding to each IMG element inthe current document
To display a new image, simply set the SRC property ofan existing image to a string representing a different
image file
M dif i I E l
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
36/84
JavaScript36 www.corewebprogramming.com
Modifying Images, Example
The following function changes the firstimage in a document
function changeImage() {
document.images[0].src = "images/new-image.gif";
}
Referring to images by name is easier:
function improveImage() {
document.images["cool"].src = "way-cool.jpg";
}
Modifying Images: A Clickable
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
37/84
JavaScript37 www.corewebprogramming.com
Modifying Images: A ClickableImage Button, Example
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
38/84
JavaScript38 www.corewebprogramming.com
y g gImage Button, Example
function clickButton(name, grayImage) {var origImage = document.images[name].src;setImage(name, grayImage);var resetString =
"setImage('" + name + "', '" + origImage + "')";setTimeout(resetString, 100);
}// -->
...
...
Highlighting Images Under the
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
39/84
JavaScript39 www.corewebprogramming.com
g g g gMouse, Example
High Peaks Navigation Bar
// Given "Foo", returns "images/Foo.gif".
function regularImageFile(imageName) {
return("images/" + imageName + ".gif");
}
// Given "Bar", returns "images/Bar-Negative.gif".
function negativeImageFile(imageName) {
return("images/" + imageName + "-Negative.gif");}
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
40/84
Highlighting Images Under the
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
41/84
JavaScript41 www.corewebprogramming.com
g g g gMouse, Example, cont.
...function highlight(imageName) {document.images[imageName].src = negativeImageFile(imageName);
}
function unHighlight(imageName) {document.images[imageName].src = regularImageFile(imageName);
}// -->
...
Highlighting Images Under the
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
42/84
JavaScript42 www.corewebprogramming.com
g g g gMouse, Result
Making Pages Dynamic:
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
43/84
JavaScript43 www.corewebprogramming.com
g g yMoving Layers
Netscape 4 introduced layers regionsthat can overlap and be positioned
arbitrarily JavaScript 1.2 lets you access layers via thedocument.layers array, each element ofwhich is a Layer object with propertiescorresponding to the attributes of the LAYERelement
A named layer can be accessed viadocument.layers["layer name"] ratherthan by using an index, or simply by usingdocument.layerName
Moving Layers Example
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
44/84
JavaScript44 www.corewebprogramming.com
Moving Layers, Example
Descriptive overlays slowly drift to final spotwhen button clicked
Camps on K-3
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
45/84
JavaScript45 www.corewebprogramming.com
Moving Layers, Example, cont.
function showBaseCamp() {hideCamps();
baseCamp = document.layers["baseCamp"];baseCamp.moveToAbsolute(0, 20);
baseCamp.visibility = "show";moveBaseCamp();}functionmoveHighCamp() {highCamp.moveBy(2, 1);if (highCamp.pageX < 110) {
setTimeout("moveHighCamp()", 10);}
}
function showHighCamp() {hideCamps();highCamp = document.layers["highCamp"];highCamp.moveToAbsolute(0, 65);highCamp.visibility = "show";
moveHighCamp();
}// -->
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
46/84
Moving Layers Result
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
47/84
JavaScript47 www.corewebprogramming.com
Moving Layers, Result
Moving Layers Result
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
48/84
JavaScript48 www.corewebprogramming.com
Moving Layers, Result
Application: Using JavaScriptt V lid t CGI F
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
49/84
JavaScript49 www.corewebprogramming.com
to Validate CGI Forms1. Accessing Forms
The document.formsproperty contains an array ofForm entries contained in the document
As usual in JavaScript, named entries can be accessedvia name instead of by number, plus named forms areautomatically inserted as properties in the document
object, so any of the following formats would be legalto access forms
var firstForm = document.forms[0];// Assumes
var orderForm = document.forms["orders"];
// Assumes
var registrationForm = document.register;
Application: Using JavaScriptt V lid t CGI F t
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
50/84
JavaScript50 www.corewebprogramming.com
to Validate CGI Forms, cont.2. Accessing Elements within Forms
The Form object contains an elements property thatholds an array of Element objects
You can retrieve form elements by number, by namefrom the array, or via the property name:
var firstElement = firstForm.elements[0];
// Assumes
var quantityField = orderForm.elements["quantity"];
// Assumes var submitButton = register.submitSchedule;
Checking Form ValuesI di id ll E l
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
51/84
JavaScript51 www.corewebprogramming.com
Individually, ExampleOn-Line Training
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
52/84
JavaScript52 www.corewebprogramming.com
Individually, Example, cont.// -->
On-Line Training
To see an introduction to any of our on-line trainingcourses, please enter the name of an important Web
programming language below.
Language:
Checking Form ValuesIndividually Results
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
53/84
JavaScript53 www.corewebprogramming.com
Individually, Results
Checking Values When Form isSubmitted Example
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
54/84
JavaScript54 www.corewebprogramming.com
Submitted, ExampleCamp Registration
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
55/84
Checking Values When Form isSubmitted Results
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
56/84
JavaScript56 www.corewebprogramming.com
Submitted, Results
Application: Using JavaScriptto Store and Examine Cookies
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
57/84
JavaScript57 www.corewebprogramming.com
to Store and Examine Cookies1. Using document.cookies
Set it (one cookie at a time) to store valuesdocument.cookie = "name1=val1";
document.cookie = "name2=val2; expires=" + someDate;
document.cookie = "name3=val3; path=/;domain=test.com";
Read it (all cookies in a single string) to access values
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
58/84
Cookie, Example
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
59/84
JavaScript59 www.corewebprogramming.com
Widgets "R" Us
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
60/84
JavaScript60 www.corewebprogramming.com
function cookieVal(cookieName, cookieString) {
var startLoc = cookieString.indexOf(cookieName);
if (startLoc == -1) {
return(""); // No such cookie
}
var sepLoc = cookieString.indexOf("=", startLoc);
var endLoc = cookieString.indexOf(";", startLoc);
if (endLoc == -1) { // Last one has no ";"
endLoc = cookieString.length;
}
return(cookieString.substring(sepLoc+1, endLoc));}
function presetValues() {
var firstField = document.widgetForm.firstField;
var lastField = document.widgetForm.lastField;var accountField = document.widgetForm.accountField;
var cookies = document.cookie;
firstField.value = cookieVal("first", cookies);
lastField.value = cookieVal("last", cookies);
accountField.value = cookieVal("account", cookies);
}
// -->
Cookie, Exmaple, cont.
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
61/84
JavaScript61 www.corewebprogramming.com
Widgets "R" Us
First Name:
Last Name:
Account Number:
Widget Name:Cookie, Example, Result
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
62/84
JavaScript62 www.corewebprogramming.com
Application: Using JavaScriptto Interact with Frames
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
63/84
JavaScript63 www.corewebprogramming.com
to Interact with Frames Idea
The default Window object contains a framespropertyholding an array of frames (other Window objects)contained by the current window or frame.
It also has parent and top properties referring tothe directly enclosing frame or window and the top-level window, respectively.
All of the properties of Window can be applied to anyof these entries.
Displaying a URL in a ParticularFrame Example
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
64/84
JavaScript64 www.corewebprogramming.com
Frame, Example ShowURL.html
Show a URL
Displaying a URL in a ParticularFrame, Example, cont.
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
65/84
JavaScript65 www.corewebprogramming.com
Frame, Example, cont. GetURL.html
Choose a URL
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
66/84
JavaScript66 www.corewebprogramming.com
Frame, Example, cont. GetURL.html, cont.
Choose a URL
URL:
Displaying a URL in a ParticularFrame, Result
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
67/84
JavaScript67 www.corewebprogramming.com
Frame, Result
Displaying a URL in a ParticularFrame, Result, cont.
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
68/84
JavaScript68 www.corewebprogramming.com
Frame, Result, cont.
Giving a Frame the Input Focus,Example
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
69/84
JavaScript69 www.corewebprogramming.com
p If JavaScript is manipulating the frames, the
fix is easy: just add a call to focus inshowUrl:function showURL() {
var url = document.urlForm.urlField.value;
parent.displayFrame.location = url;
// Give frame the input focus
parent.displayFrame.focus();
}
Fixing the problem in regular HTMLdocuments is a bit more tediousRequires addingonClick handlers that call focus to
each and every occurrence of A and AREA that includes a
TARGET, and a similaronSubmit handler to eachFORM that uses TARGET
Application: Accessing Javafrom JavaScript
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
70/84
JavaScript70 www.corewebprogramming.com
p1. Idea
Netscape 3.0 introduced a package called LiveConnectthat allows JavaScript to talk to Java and vice versa
Applications: Calling Java methods directly.
In particular, this section shows how to printdebugging messages to the Java console
Using applets to perform operations for JavaScript In particular, this section shows how a hidden
applet can be used to obtain the clienthostname, information not otherwise available to
JavaScript Controlling applets from JavaScript
In particular, this section shows howLiveConnect allows user actions in the HTML
part of the page to trigger actions in the applet
Application: Accessing Javafrom JavaScript
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
71/84
JavaScript71 www.corewebprogramming.com
p Calling Java Methods Directly
JavaScript can access Java variables and methods simplyby using the fully qualified name. For instance:
java.lang.System.out.println("Hello Console");
Limitations: Cant perform operations forbidden to applets
No try/catch, so cant call methods that throwexceptions
Cannot write methods or create subclasses
Controlling Applets fromJavaScript, Example
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
72/84
JavaScript72 www.corewebprogramming.com
p , p MoldSimulation.html, cont.
Mold Propagation Simulation
< HTML>
Controlling Applets fromJavaScript, Example
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
73/84
JavaScript73 www.corewebprogramming.com
p , p MoldSimulation.html
Mold Propagation Simulation
Controlling Applets fromJavaScript, Example
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
74/84
JavaScript74 www.corewebprogramming.com
p p RandomCircles.java
public class RandomCircles extends Applet
implements Runnable {
private boolean drawCircles = false;
public void startCircles() {Thread t = new Thread(this);t.start();
}
public void run() {Color[] colors = { Color.lightGray, Color.gray,
Color.darkGray, Color.black };
int colorIndex = 0;int x, y;int width = getSize().width;int height = getSize().height;
Graphics g = getGraphics();drawCircles = true;...
Controlling Applets fromJavaScript, Example
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
75/84
JavaScript75 www.corewebprogramming.com
RandomCircles.java
public class RandomCircles extends Applet
implements Runnable {
private boolean drawCircles = false;
public void startCircles() {Thread t = new Thread(this);t.start();
}
public void run() {Color[] colors = { Color.lightGray, Color.gray,
Color.darkGray, Color.black };
int colorIndex = 0;int x, y;int width = getSize().width;int height = getSize().height;
Graphics g = getGraphics();drawCircles = true;...
Controlling Applets fromJavaScript, Example
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
76/84
JavaScript76 www.corewebprogramming.com
RandomCircles.java, cont.
while(drawCircles) {
x = (int)Math.round(width * Math.random());
y = (int)Math.round(height * Math.random());g.setColor(colors[colorIndex]);colorIndex = (colorIndex + 1) % colors.length;g.fillOval(x, y, 10, 10);
pause(0.1);
}}
public void stopCircles() {drawCircles = false;
}
private void pause(double seconds) {try {
Thread.sleep((int)(Math.round(seconds * 1000.0)));} catch(InterruptedException ie) {}
}}
Controlling Applets fromJavaScript, Results
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
77/84
JavaScript77 www.corewebprogramming.com
Accessing JavaScript fromJava
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
78/84
JavaScript78 www.corewebprogramming.com
Steps1. Obtain and install theJSObject class
Installed with Netscape (javar40.jar)
2. Import it in your appletimport netscape.javascript.JSObject
3. From the applet, obtain a JavaScript reference to thecurrent window
JSObject window = JSObject.getWindow(this);
4. Read the JavaScript properties of interest
Use getMember to access properties of theJSObjectJSObject someForm =
(JSObject)document.getMember("someFormName");
Accessing JavaScript fromJava, cont.
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
79/84
JavaScript79 www.corewebprogramming.com
Steps, cont.5. Set the JavaScript properties of interest
Use setMember to set properties of theJSObjectdocument.setMember("bgColor", "red");
6. Call the JavaScript methods of interestString[] message = { "An alert message" };
window.call("alert", message);window.eval("alert(An alert message)");
7. Give the applet permission to access its Web page
...
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
80/84
Matching Applet Backgroundwith Web Page, Example, cont.
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
81/84
JavaScript81 www.corewebprogramming.com
MatchColor.html
MatchColor
MatchColor
Applet That Controls HTMLForm Values, Example
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
82/84
JavaScript82 www.corewebprogramming.com
See on-line example for Everest.html
Summary
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
83/84
JavaScript83 www.corewebprogramming.com
JavaScript permits you to:Customize Web pages based on the situation
Make pages more dynamicValidate HTML form input
Manipulate cookies
Control frames Integrate Java and JavaScript
core
-
8/11/2019 JavaScript - Adding Dynamic Content to Web Pages - Core Web Programming - Chapter 24
84/84
84 2001-2002 Marty Hall, Larry Brown http://www.corewebprogramming.com
programming
Questions?