Anda di halaman 1dari 17

Programming Web Pages with JavaScript

Until recently, Web-site design was limited by the


constraints of HTML and CGI. JavaScript is an easy-to-use
language, developed by Netscape, which can be embedded
in HTML pages to make them more interactive and
dynamic.
JavaScript allows site designers with moderate programming
skills to add capabilities to their Web pages, including
instant user feedback, advanced form processing, pop-up windows, advanced
frame applications, and much more. You learn the basic elements of the JavaScript
language and several techniques to take your Web pages to the next level.
Prerequisite: Familiarity with HTML and Web page design. Some programming
experience in C, Visual Basic, or the equivalent.
MICHAEL WOLFE, M.S., is Vice President of Engineering at Kana
Communications, a startup software company focusing on enterprise email support
solutions. He has been teaching computer science and developing industrial
systems for 10 years at Stanford University, Goldman Sachs, and Wells Fargo. His
prior position was as a Director of Engineering of Internet Profiles Corp.
2 days, Feb. 6-7, 8:30 am-5:30 pm
Introduction
This is "Enhancing WWW pages with JavaScript".
These notes are at http://www-cs-students.stanford.edu/~wolfe/javascript/
This is a laboratory class. You will be doing many hands-on exercises and
looking at many examples.
Prerequites: HTML skills, some programming experience, and good PC
skills. I will not be able to spend time teaching the basics.
We will not learn the entire JavaScript language, but we will learn the
primary techniques for enhancing WWW pages with JavaScript.
Software requirements: an editor (notepad, Frontpage, etc.) and a WWW
browser (IE 4.0 or NS 4.0). If you log in as 'internet' you should have access
to these things.
Class Outline
What is JavaScript? JavaScript examples
JavaScript language fundamentals
Browser object model in Netscape and Internet Explorer
Using JavaScript with HTML Forms
JavaScript Events
JavaScript Frames and Windows
JavaScript is a language
Invented by Netscape in 1995 in Navigator 2.0.
Designed as a browser, client-side scripting language for the Web,
supplementing HTML.
Similar syntax to C, C++, and Java.
Interpreted, scripting language, not a full programming language.
Platform-independent.
Also has been adopted by Microsoft: they call it "JScript".
Has been proposed as a standard called ECMAScript. MS and NS are
working to make their implementations comply with the standard.
Not really related to Java.
Both client-side (browser-based) JavaScript and server-side JavaScript.
Most focus is on the client.
JavaScript is a way to enhance WWW pages within a WWW browser
Netscape and Microsoft both enabled brower elements to be controlled by
JavaScript.
Pop-ups windows, form verification, dynamic pages...often those effects are
created by JavaScript.
Netscape and Microsoft browsers support JavaScript 1.1. The 1.2 release
came out with Netscape 4.0.
But it is supported very unevenly between operating systems and between
Netscape and Microsoft.
Alternatives: CGI, Java, VBScript, Dynamic HTML, ASP.
JavaScript can also be used elsewhere
As a server-side scripting language for Microsoft Active Server Pages.
As a server-side scripting language in Netscape Livewire.
As a scripting language embedded in other applications.
Examples
http://www.livesoftware.com/jrc/
http://www.calpoly.edu/~dpopeney/javascript.html
Kana Communications
Resources
http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html
http://msdn.microsoft.com/scripting/
http://www.developer.com/
http://www.yahoo.com/Computers_and_Internet/Programming_Languages/J
avaScript/
JavaScript contains many of the same elements that other programming
languages do:
variables, constants (pieces of data)
data structures like array and objects (ways to hold together and access
bigger sets of data)
user-defined functions
built-in functions (math, dates, etc.)
operators (+,-,/,*)
statements (if, while, for)
object-based programming (but not fully object-oriented)
But, it is most powerful when the language elements are combined with the
"browser object model":
HTML
Windows
Frames
Hyperlinks
Forms
Page elements
Your first program
One way to put JavaScript in a page is with the <SCRIPT> tag
Start tag with <SCRIPT LANGUAGE="javascript">
End tag with </SCRIPT>
Put JavaScript between the tags.
There are several places on an HTML page where script tags can go, and a
page will often have several.
A simple example:
<SCRIPT LANGUAGE="javascript">
document.write("Hello, world")
</SCRIPT>
Output:
Hello, world
Assignment:
1. Create a working folder on your PC for your JavaScript exercises.
2. You do not necessarily need to run a WWW server to develop JavaScript,
since you can do it all locally. If you want to run one for practice, go ahead.
3. Open the text editor of your choice (notepad, Frontpage, etc.)
4. Make a blank HTML page.
5. Copy this example into it.
6. Load the page into your browser, and watch it go.
Other examples, using simple expressions
<SCRIPT LANGUAGE="javascript">
// This JavaScript illustrates some simple concepts
document.write("<B>Hello, bold world</B><BR>") // Print text with an HTML tag
document.write("Two plus two is " + (2+2) + "<BR>") // Print the result of a mathematical expression
document.write("Your browser says it is: "\" + navigator.userAgent +
"\"<BR>") // Print one of the browser properties.
</SCRIPT>
Output:
Hello, bold world
Two plus two is 4
Your browser says it is: "Mozilla/5.0 (Windows NT 6.3; WOW64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143
Safari/537.36"

The alert(), confirm(), and prompt() functions, with an if-else example
We are first going to look at some examples of JavaScript functions. A function is
an expression that does something...kind of like a verb. Several functions are either
built into the JavaScript language or are built into the browsers in which JavaScript
runs. Most of the useful functions, including the ones we are looking at here, are
built into both the Netscape and Microsoft browsers. We can look at the notes
at Netscape to see how these functions work. Go under Part 13 to see links to all
available functions, including alert(), confirm(), and prompt(). Use that
documentation to figure out how the following code works.
var yourName; // Declare a variable
called yourName, which will store your name after you type it in
yourName = prompt("What is your name?", ""); // Now read the name
from the user and store it

if (confirm("Do you want to play a game, " + yourName + "?")) // Ask
if the user wants to play. confirm() returns either true or false
{
alert("OK. let's play, " + yourName); // alert() pops up a
browser dialog box
}
else
{
alert("Too bad!");
}

The JavaScript above is on this page.

Operators and expressions
JavaScript has all of the usual mathematical and logical operators. Please see
documentation at Part 7, "Expressions and Operators" at the Netscape notes.

+, -, /, % (arithmetic)
>, <, >=, lt=, ==, != (comparisons)
&&, ||, ! (boolean)


Another example, using a variable and the if-else statement.
The if-else statement is documented at the Part 11, "Statements".

// This is a comment (starting with a // on the same line)
// here, we hardcode the right answer (but, JS also has a Random() function
you could use to generate a new one each time)
var rightAnswer = 57;

var num = prompt("Please guess a number below 100: ","");

/* This is another comment. You would use this syntax for
a comment that spans multiple lines */

if (num < rightAnswer)
{
alert("Your guess was too low");
}
else if (num > rightAnswer)
{
alert("Your guess was too high");
}
else
{
alert("Congratulations!");
}

Assignment:
Build a program that does the following:
1. Asks the user for a measurement in inches.
2. Tells the user the same measurement in centimeters(multiply by 2.54).
A solution.
A user-defined function, and a while loop:
In JavaScript, you can create your own functions. See the notes for function() and
for the while() statement at the Netscape notes at Part 11, "Statements".
var MIN = 1;
var MAX = 10;

function goodGuess(num)
{
return (num >= MIN && num <= MAX);
}

var guess = prompt("Please enter a number between " + MIN + " and " +
MAX,"");

while (!goodGuess(guess))
{
guess = prompt("That guess was not between " + MIN + " and " + MAX + ",
please try again.","");
}
Assignment:
Write a program to:
1. Choose and store a random number between 1 and 1000.
2. Allow the user to choose the number until getting it right.
3. Tell the user in each turn whether the guess was too high or too low.
Hints:
1. Declare a variable to store the random number and populate it using the
Math.random() function.
2. The Math.floor( ) function rounds a number down to the next integer. You
will need to use this.
3. Write a function to give user feedback on whether the number was too high
or too low and return a true if the answer was correct and false if it was not.
4. Use a while loop to play the game until the user gets the right answer.
A solution.
The for loop
See the notes for for at the Netscape notes at Part 11, "Statements".

var MAX = 10;
var count;
for (count = MAX; count >= 1; count--)
{
document.write("Countdown: " + count + "<BR>");
}
Output:
Countdown: 10
Countdown: 9
Countdown: 8
Countdown: 7
Countdown: 6
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1

The most important JavaScript object: String().
An object is a programming construct that usually represents a real world concept.
An object, in most languages, can contain data (the current object state) and
methods, which are functions that can be called upon that object. Several objects
are defined by JavaScript, several more are provided by the browser, and
a developer can create objects.
Strings are used everywhere in JavaScript. See the notes for String at the Netscape
notes at Part 13, "Netscape JavaScript Reference".
The String constructor:
The constructor is the operator to create a new instance of an object. Each object is
documented with all of its various constructors.
var str = new String("Hello"); // The basic constructor
var str2 = "Hello"; // This is shorthand and is what is usually
used
String properties methods:
The String object is documented with a set of methods and properties it has
available. In particular, length, indexOf(), toUpperCase(), and toLowerCase() are
useful.

alert("Your name is " + str.length + " characters long");
alert("Your name in uppercase is " + str.toUpperCase());
Browser detection:

<SCRIPT LANGUAGE="javascript">

// Print out the browser name and version (these are properties of the
object called 'navigator'
document.write(navigator.appName + "< BR>")
document.write(navigator.appVersion + "<BR>")

if (navigator.appName.indexOf("Netscape") != -1)
{
document.writeln("You are using Netscape.<BR>");
}
else
{
document.writeln("You are not using Netscape.<BR>");
}
</SCRIPT>
Output:

Netscape
5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/36.0.1985.143 Safari/537.36
You are using Netscape.

Assignment: Look at the documentation for the String class at the Netscape notes
and write a script to:
Ask the user for his/her name.
Tell the user how long the name is.
Print the name in uppercase and lowercase.
Print the first character of the name.
Say whether the name contains the letter 'a'.
Say whether the user is a Netscape or Internet Explorer user.
Say whether the user is a Windows NT user.
Hint: see these notes under User Info for common browser and OS strings.
Another JavaScript Object: the Date() class
One object built into JavaScript is Date. See the notes for Date at the Netscape
notes at Part 13, "Netscape JavaScript Reference".
Date example
var d = new Date(); // With an empty constructor, default to the current
date
document.write("<h3>" + d.toString() + "</h3>");
Output:
Mon Aug 25 2014 23:22:38 GMT+0530 (India Standard Time)
Assignment:
Write a program that:
1. Asks the user for the current date in the format MM/DD/YYYY.
2. Tells the user how many days it is until the new year.
Hints:
1. There is a method of String called 'substring' which you can use to parse the
user input.
2. There is a Date() constructor which takes a year, month, and date as an
argument.
3. Look at the getTime() method of Date.
4. Use Math.floor() for rounding.
Solution.
Browser object model in Netscape and Internet Explorer.
Each major browser (Netscape 2.0, 3.0, 4.0 and Internet Explorer 3.0 and 4.0)
exposes the major browser elements as an API (application programming
interface) that the programmer has access to read and, sometimes, write to. They
are charted as follows:
Netscape Navigator browser object model
Example: attributes of this page
document.write("window.location: <B>" + window.location + "</B><BR>");
document.write("window.document.referrer: <B>" + window.document.referrer +
"</B><BR>");
document.write("window.document.bgcolor: <B>" + window.document.bgcolor +
"</B><BR>");
document.write("navigator.appName: <B>" + navigator.appName + "</B><BR>");
document.write("navigator.appVersion: <B>" + navigator.appVersion +
"</B><BR>");
Output:
window.location: http://www-cs-students.stanford.edu/~wolfe/javascript/
window.document.referrer: https://www.google.co.in/
window.document.bgcolor: undefined
navigator.appName: Netscape
navigator.appVersion: 5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36

Example: looping through all of the links in a document
var count;
for (count=0; count< window.document.links.length;count++)
{
document.write("Link " + count + ": " +
window.document.links[count]+"<BR>");
}
Output:
Link 0: http://www-cs-students.stanford.edu/~wolfe/javascript/
Link 1: http://www.jsworld.com/ecmascript/
Link 2: http://www.livesoftware.com/jrc/
Link 3: http://www.calpoly.edu/~dpopeney/javascript.html
Link 4: http://www.kana.com/
Link 5: http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html
Link 6: http://msdn.microsoft.com/scripting/
Link 7: http://www.developer.com//
Link 8:
http://www.yahoo.com/Computers_and_Internet/Programming_Languages/JavaSc
ript/
Link 9: http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html
Link 10: http://www-cs-students.stanford.edu/~wolfe/javascript/exercise1.html
Link 11: http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html
Link 12: http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html
Link 13: http://www-cs-students.stanford.edu/~wolfe/javascript/convert.html
Link 14: http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html
Link 15: http://www-cs-students.stanford.edu/~wolfe/javascript/guess.html
Link 16: http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html
Link 17: http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html
Link 18: http://www.calpoly.edu/~dpopeney/javascript.html
Link 19: http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html
Link 20: http://www-cs-students.stanford.edu/~wolfe/javascript/newyears.html
Link 21:
http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/navobj.htm

Example: the status bar
The status bar for a window can be accessed as the 'status' field of the current
window (window.status).
Example:
Move your mouse over <A HREF="http://www.examiner.com"
onMouseOver="window.status='Click for the examiner'; return true">here</A>
and watch the status bar.
Output:
Move your mouse over here and watch the status bar.
Events.
Events are asynchronous actions that happen when the user interacts with a page
by typing, clicking, moving the mouse, or loading and unloading a page. Events
can also be driven by timers. A reference of events can be found at the Netscape
JavaScript documentation.
Syntax of event handlers:
For hyperlinks:
<A HREF="URL" event="some javascript">
For form elements:
<INPUT TYPE="type" NAME="name" event="some javascript">
The onClick() event, with a hyperlink:
<A HREF="index.html" onClick="alert('Thanks for clicking'); return
true;">Click for a test</A><P>
Note: if the JavaScript called from the onClick event returns a true value, the link
is followed. Otherwise, it is not.
Try it:
Click for a test
Assignment:
Create a hyperlink where the user is first warned "are you sure?" before the link is
followed. If the user cancels, then the link is not followed.
Create another hyperlink where the user gets asked a "secret" password before
continuing. If the user gets the password right, the link is followed.
Solution.
The onMouseOver() event:
<SCRIPT LANGUAGE="javascript">
function oops()
{
alert("You got too close!")
}
</SCRIPT>

<A HREF="somepage.html" onMouseOver="oops()">Move mouse over this for a
test</A>

Try it:
Move mouse over this for a test
The onChange() event:
<FORM NAME=myform>
<INPUT TYPE="text" NAME="text1" onChange="document.myform.text2.value =
document.myform.text1.value"><BR>
<INPUT TYPE="text" NAME="text2">
</FORM>
Result:
FROM Field:
TO Field:
The setTimeout() function
Try the following code:
setTimeout("alert('Time is up')",2000)
Assignment:
Write a program to put an updating timer on the status bar
Hint: window.status is the property that controls the status bar
Hint: you need to write a function, but only one function
Solution.
The onLoad() function
This event occurs when the page has been fully loaded. Pages can take a long time
to load, and there are often times when you don't want to execute a command until
the page is done loading. Try the following code somewhere in the BODY tag on
your page:
<BODY onLoad="window.status = 'Fully loaded!'">
Forms
Much JavaScript interaction is done via HTML forms and their familiar elements:
buttons, text boxes, radio buttons, check boxes, text boxes, etc. In JavaScript it is
possible to control these elements as well as respond to events triggered from these
elements.
The documentation for the browser object models will show you the object
hierarchy for reading and setting form elements.
JavaScript is often used for validating fields in forms. The following example
shows how JavaScript can be used to validate the email address of a form in the
user's browser before it gets submitted to the server:
E-mail address validation example:
<SCRIPT LANGUAGE="javascript">

// Check for a valid email address (Does it contain a "@", followed
// by a '.'. Return True if it is valid and false if not.
// Also alert the user with an error message.
//
function checkEmail(theField)
{
if (theField.indexOf('@', 0) > 0 && (theField.indexOf('.',0) >
theField.indexOf('@',0)))
{
return true;
}
else
{
alert("Your email address was an invalid format. Please try
again.");
return false;
}
}
</SCRIPT>

<FORM NAME=emailform ACTION="yourcgihere.cgi" METHOD=POST onSubmit="return
checkEmail(window.document.emailform.emailAddress.value)">
Please enter your email address:<P>
<INPUT TYPE=text NAME="emailAddress" VALUE=""><P>
<INPUT TYPE=submit NAME="Submit" VALUE="Submit">
</FORM>
Output:
Please enter your email address:

Submit

Assignment:
1. Copy this form to your own page.
2. Add a phone number field.
3. Add a routine to validate phone number (format XXX-XXX-XXXX)
Solution.
A library of form validation routines can be found at the Netscape WWW site.
Calculator examples
These are examples of forms that do not send any data to the server but tries to do
a useful operation in the browser itself.
This is an example of a mortgage calculator.
<SCRIPT>
function doCalculate()
{
var val1, val2
var result
val1 = parseInt(document.calcForm.val1.value)
val2 = parseInt(document.calcForm.val2.value)
if (document.calcForm.op[0].checked)
{
result = val1 + val2
}
else
{
result = val1 - val2
}
document.calcForm.result.value = result
}
</SCRIPT>

<FORM NAME="calcForm">
Value 1:<INPUT TYPE=text NAME="val1" SIZE=6><P>
Add:<INPUT TYPE=radio NAME="op" VALUE="plus">
Subtract:<INPUT TYPE=radio NAME="op" VALUE="minus"><BR>
Value 2:<INPUT TYPE=text NAME="val2" SIZE=6><BR>
Result:<INPUT TYPE=text NAME="result" SIZE=10><BR>
<INPUT TYPE=button NAME="calculate" VALUE="Calculate"
onClick="doCalculate()">
</FORM>
Result:
Value 1:
Add: Subtract:
Value 2:
Result:

Assignment:
1. Copy this form to your own HTML page
2. Add multiplication and division to the form
3. When you have this working, get rid of the 'Calculate' button, and make it so
that the calcuation happens whenever you make a change to either value or
click on the radio button.
4. Hint: use the onChange event for the text fields, and use the onClick event
for the radio buttons
Solution.
Another example of a form similar to this one is at this uppercase/lowercase form.
Assignment:
1. Build a inches to centimeters form with 2 text boxes
2. Make it so that when you change the inches field, the proper conversion to
centimeters is written into the centimeters box
3. And, vice-versa
Solution.
Frames and windows
JavaScript is very commonly used to control pages with complex frame layouts
and to control multiple windows.
Frame manipulation:
Real-world example:
Please look at this example at The Nature Conservancy. It is a great example of
using multiple frames on a page with JavaScript for a very useful and interesting
effect.
Example:
An example that does frame manipulation is on this page.
Assignment:
1. Create a frameset that has two frames, side by side.
2. Make the left-hand frame contain a form with 3 radio buttons
3. The buttons should be for three search engines:
o Yahoo (http://www.yahoo.com)
o Altavista (http://www.altavista.com)
o Infoseek (http://www.infoseek.com)
4. When the user clicks on of the option buttons, the frame on the right hand
side should be loaded with the right search engine.
Solution.
Manipulating images
There are two ways to change an image on a WWW page using Javascript:
1. Use frames, and put each image in a different frame.
2. Change the image directly (only works in NS 3.0 and beyond and IE 4.0).
Example that will replace the first graphic on a page (image.gif) with another
graphic (newgraphic.gif):
<IMG SRC="image.gif">

<SCRIPT LANGUAGE="javascript">
document.images[0].src = "newgraphic.gif"
</SCRIPT>
Exercise:
Build a WWW page with an image and 3 buttons.
Pick your three favorite graphics out on the WWW.
Label the buttons and make each one swap in the graphic you have chosen.
Solution.
Opening and manipulating windows
The function to open a new window is 'window.open()'. Syntax and options are
at Netscape.
Usage:
var win = window.open(URL, name, options)
Example:
See notes on this page.
Assignment:
First, write a simple (one-line) JavaScript program to experiment with opening a
window. Try all of the different options that you can (width, height, toolbars,
location, status, resizable, etc.).
Repeat the assignment with the three search engines. Add two buttons, one to open
a search engine window, and one to close it (use the close() method of window).
Make it so that selecting the the radio button fills in the pop up window with the
right site.
Another idea: pop up a very small "remote control" window. Allow the user to type
a URL into that window to change the location of the larger window.

Anda mungkin juga menyukai