Topic JavaScript

advertisement
JavaScript
JavaScript
Introduction
JavaScript
An object-oriented scripting language, commonly used in html
pages, to provide dynamism or forms of dynamism not supported by html.
JavaScript is not Java. We’ll use JavaScript as an introduction to certain program‐
ming concepts and to the idea of expanding HTML’s possibilities. Before tacking
this module, you should be comfortable with HTML and CSS.
Follow-up courses
Web Scripting, Digital Libraries, Multimedia Info Systems, Information
Architecture, XML
Anyone in information work today is expected to have at least a passing knowledge of scripting and
programming concepts, ability to use basic scripts in their websites, and understand the relationship
between data, users, and interactivity. In this module we introduce the absolute rudiments of these
concepts. As you advance in LIS, you’ll encounter XML. XML works extremely closely with JavaScript, Ajax,
and Java in the web as a client/server model.
Readings
Complete this module and
Complete the JavaScript module at http://www.w3sschools.com
JavaScript is a scripting language, as are PHP, perl, ActionScript, and ColdFusion. Scripting languages , like
all programs, are compiled, meaning the programmers’ source code is converted into something by a tool
(software called a compiler) that can be understood by the computer. But scripts are not run trough the
compiler and read until they’re actually called. For example, if your web page has a Java Script, it isn’t read
by the browser and performed until the browser finishes loading the web page. If there’s a mistake in the
program, only then it is found. Compiled programs, on the other hand, are submitted to a “two-pass
compilation” and then “object” or “binary” code produced. For example, a word processing program was
written, probably, in C++ with some routines written in Assembler, and then compiled. The compiler
program checks that the programmer used the language’s syntax correctly and then passes through the
code to optimize it and produce code that can be read by the computer’s chip (CPU). For example,
programmers use a particular programming language they think is best suited for the task, say C++ or Java.
They write “source code” in that language (see Topic Web-enabled DB for a Java sample). The compiler
checks the code and then outputs “object code.” In C++, for example, the source code might be stored in a
file called “myfile.cpp”. The compiler reads the .cpp file and outputs an object file. A Java program ends in
“.java”. Then the Java compiler converts the code into a .class file. The upshot is this: scripting languages
are usually easier to learn and apply but are slower to run. Compiled languages are usually more complex
but do far more than scripts and run more quickly.
JavaScript. The most common use of JavaScript is to add some kind of dynamism to web pages (.html).
How come? Browsers are programmed to understand HTML and CSS and they have built-into them
JavaScript interpreters. Like compilers, interpreters read the code, check its syntax, and then execute the
code. We must inform the browser that we want to call the interpreter by using the HTML tag <script>.
Here’s an example of an elementary web page (.html) that calls a JavaScript to in turn creates a dialog box
(an “alert box”) to appear on the screen and to welcome us:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://wwww3.org/TR/
html4/strict.dtd">
<html>
<head>
1
JavaScript
<title>My first demo JavaScript</title>
<script type="text/javascript">
alert('Hello, visitor to my web page.');
</script>
</head>
[Note! Most word processing programs convert the apostrophe ' and quotes into a “smart quote” (e.g., “ ” ).
Be aware of this and disable this option through the program’s preference pane. The code for the “smart
apostrophe” is not the same as the plain quote and the program will not run.]
As you know, web pages reference documents and items, such as image files and other websites, that are
not part of the webpage. This means the website calls an external file. The same way HTML lets you call
an external CSS, so you can call an external JavaScript program. JavaScript programs are stored in files
with .js extension, e.g., “myWelcome.js”:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://wwww3.org/TR/
html4/strict.dtd">
<html>
<head>
<title>My first demo JavaScript</title>
<script type="text/javascript" src="myWelcome.js">
</script>
</head>
Work through …
First work through http://www.w3sschools.com/ tutorial on JavaScript.
JavaScript is used in web pages to provide more interactivity and dynamism to the static HTML pages. It is
useful as an introduction to scripting and programming and a great way to become confident in taking
other technical courses and taking control of the uses of technology, rather than be at the mercy of an IT
staff.
JavaScript Grammar All programming languages have a syntax - the rules. The first thing is to know the
four main components of any program:
statements: a basic unit, representing a step, e.g., alert(‘Hello there!’); Statements end in a semi-colon.
commands: commands make things happen; they’re functions. Recognize them by the use of parentheses
(). Data passed to the function for its purposes are called parameters and are contained within the
parentheses: the ‘Hello there’ in the above example is a “String parameter”, passed to the “alert() command.”
Types of data: The parameters and variables come in different types. See the Topic DataTypes for more info.
For the moment, let’s look at two kinds: Numbers and Strings. A number is used for calculating or
counting. JavaScript is not “strongly-typed” meaning you can be pretty sloppy with your definitions of
variables, but it is better to know about data types in case something goes wrong. For example, there’s an
object called “document” that is built into the web browser. The document object has its own functions,
one of them is “write” (meaning “print data on the screen”). We can pass numbers or Strings as parameters
and do something with them. In this example, we want the results of adding 5 + 10 to appear (“to be
written”) on the screen of the web browser: document.write(5 + 10); The browser’s JavaScript
interpreter first adds 5 + 10 (and stores it in memory as 15); then the browser prints on the screen the result
2
JavaScript
(15). Strings in JavaScript, unlike other programming languages, are indicated by double quotes or single
quotes! For example, var myName = "Jane Smith"; is the same as var myName = 'Jane Smith';.
[Note: sometimes you want to use quotes within quotes - don’t! Switch between double quotes and single
quotes: If you want an alert box to show (“Well, Tom. The password is “cats rule”.”), you’ll have to alternate
quotes: alert("Well, Tom. The password is 'cats rule'."). [Note that “document.write()” erases everything on
the screen first and then displays only what is in the parentheses.]
Boolean: a Boolean variable that can hold only one of two values: true or false.
Variables: A variable is an address in the computer’s memory, identified by a name (e.g., password) and a
value (e.g., “938sk1”). Variables are assigned a data type (e.g., String, integer, float, double, boolean, among
others or the programmer creates his own Object type and uses that; see the Topic DataTypes). Variables
are first declared and then instantiated: the declaration tells the program you want to make a variable of a
certain type with a particular name; when you instantiate it, you assign a value to the variable name. In
JavaScript, use the reserve word “var” to let JavaScript know you’re creating a variable. Note that variable
names must begin with a letter, $, or _. They cannot have spaces and are case sensitive; Strings use " ";
numbers do not.
var myName = "Jane Smith"; var salary = 25.10;
Variables can be declared in two steps:
var myName;
myName = "Thomas Mann";
or in one step:
var myName = "Matt Damon";
You can declare variables and then using operators combine them or perform arithmetic functions:
+
add
e.g., 5 + 10; lastName + " " + firstName;
Only numbers can be subtracted, multiplied, divided or have a modulo:
subtract
e.g., 10 - 5;
*
multiple
e.g., 10 * 5;
/
divide
e.g., 10 / 5;
%
modulo
e.g., 25 % 5;
Or multiples at the same time:
var x, y, z;
var checkHasPrinted, salaryHasBeenPaid = false;
[here 2 variables are declared and both assigned the boolean value of “false”.]
When you declare a function or use one from a library of prepared functions created by others, you must
know what kind of data type the function has been programmed to accept. The “alert()” function is
preprogrammed to accept only String data, so this example is correct: alert(“Welcome to class.”);
You cannot say alert(53); .
It is very common in JavaScript to combine Strings and numbers: “You’ve checked out 5 items.” could be a
combination of the String and a number variable.
3
JavaScript
var checkOutString = "You\'ve checked out ";
var no_of_items = 5;
var endOfString = " items";
to create
document.write( checkoutString + " " + no_of_items + " " + items );
Notice we had to embed spaces between the words.
We combine numbers, too, in a similar way. We can add a literal number (e.g., 5) to a variable that contains
a number value (e.g., var no_of_items) to get var total = no_of_items + 5;
Sometimes you need to convert a variable that is a string into a number. We do this by using a function
called “Number()”. Say we have a variable var otherItems = ‘5’ and we want to add this to
no_of_items. We can convert the string “otherItems” into a number by passing the String as a parameter to
the Number() function: Number( otherItems ). We can do arithmetic on it, too: var newTotal =
Number(otherItems) + no_of_items.
You can update a variable anytime by changing its contents: var myName = “Smith”; can be changed by
entering myName = “Jones”; var number = 5; can be changed by saying number = 25; A number
variable can refer to itself, too: var myNumber = 5; myNumber += 5 means take the variable myNumber
(which is 5) and now add 10 to it, to make myNumber = 15;
There are six type shortcuts:
+=
Adds the value on the right to the value on the left; e.g., items += 5
This is the same as typing items = items + 5;
-+
Subtracts the values
*=
Multiples them
/=
Divides them
++
Adds 1 to the variable, e.g., if items = 5, then items++ now equals 6.
-Subtracts 1 from the variable, e.g., if items = 5, then items-- equals 4.
Lab Example 1a: Using a text editor (such as WordPad, NotePad, TextEdit, BBEdit, TextWrangler - but not
Microsoft Word or another word processing program) create your own web page for testing JavaScripts.
Follow this model:
<html><head><title>My test page</title>
</title></head>
<body>
This is a test of JavaScript
<script type="text/javascript">
var myFirstName = 'Jane';
// enter your real name
var myLastName = 'Smith';
document.write('<hr/>');
document.write(myFirstName + ' ' + myLastName);
</script>
</body>
</html>
4
JavaScript
Save the file as “example1.html” and open it with your browser. Try different browsers (Internet Explorer,
Safari, Opera, Firefox) and see how they respond.
Lab Example 1b: Revise your first JavaScript by providing the end-user a change to enter his or her name.
<html><head><title>My test page</title>
</title></head>
<body>
This is a test of JavaScript
<script type="text/javascript">
var name = prompt('What is your name?', '');
</script>
<script type="text/javascript">
document.write('<b>Welcome, '+ name + '</b>');
</script>
</body>
</html>
First note how we’ve included HTML tags (<b>) and string literals (Welcome, ). You can use any legitimate
HTML tag as a string - the browser knows that the < (less than) and > (greater than) signs should be
interpreted as HTML, not plain text.
Now notice we have 2 script areas. The first causes a dialog box to appear (called prompt()) that shows a
message and accepts input from the user. The input is stored in the variable “name”. Later the second
script kicks in and uses what the end-user typed (and stored in “name”) to echo the data back to the user.
Try it!
If you’ve reviewed DataTypes topic, you’re familiar at least passively with the idea of arrays. An array is just
a contiguous block of memory. Arrays are great ways to hold data that is very common or unlikely to
change. For example, say you want a list of your favorite authors or composers. You could create a String
variable for each one (e.g., var myComposer1 = "Bach, J. S.";) or create a box, as it were, that holds a
bunch of composer Strings. Here, we have extra returns just for clarity’s sake.
var myComposers = ['Bach, J. S.',
'Mozart, W. A.',
'Beethovan, L. v.',
'Wagner, R.',
'Offspring.'];
Now we have 5 strings in a single box (the array).
To get the data out of the box, we specify what number we want (called an index). For example to
get the Offspring out, let’s say we want a temporary variable “nowPlaying” and assign the name of the
group. var nowPlaying = myComposers[4]. Arrays are very common for displaying days of the month and
the months of the year.
Because computers usually start counting a 0, take away one number; The Offspring may be the
5th element, but they’re index is 4. If we want to add a new group, say “Cake”, to the array, we need to
know the size of the array and then add one, e.g., myComposers[5] = 'Cake'; If you don’t know how
5
JavaScript
large the array is - ask it! myComposers[ myComposers.length ] = 'Cake'; Notice the “myComposers”
within the brackets. The second part (.length) tells us right away we have an object (the array is an object)
and that the name of the object is myComposers. Moreover, because our myComposers copies (inherits)
JavaScripts own object called array, we inherit all the behaviors of that object, too. All objects have a built
in method of determining their length (their size). The . tells us we are accessing a method in an object.1
Lab Example 2: Revise your first JavaScript by providing creating a website for [your pretend employing]
library. Create an array of five authors. Then add text such as “This week we’re reading...” and display each
element in the array. Practice both your HTML skills and adding other Strings and numbers.
<html><head><title>Welcome to the Reading Room</title>
</title></head>
<body>
This is a test of JavaScript
<script type="text/javascript">
var name = prompt('What is your name?', '');
</script>
<script type="text/javascript">
document.write('<b>Welcome, '+ name + '</b>');
</script>
</body>
</html>
Conditional statements - control-of-flow
Everything cannot happen at the same time in a computer program: we control what happens
when by when we call an object and by using logical statements that test for certain conditions. For
example, when you get cash from the bank’s ATM machine, the ATM system must check first whether or
not you have funds to cover the request and that the request isn’t over the bank’s default limit of $300: if
you have enough money in your account to cover the request, then give her the cash.
if (you_have_enough_money)
then (give her the cash)
or in a way the computer can understand:
if ( checkIfEnoughMoney() ) {
payTheMoney();
}
Let’s try this in JavaScript:
var requestAmount = 200;
var totalInAccount = 4200;
if ( requestAmount <= totalInAccount ) {
payTheMoney();
}
In addition, there’s the consequence - what if there isn’t enough money? Let’s say the ATM has an alert box
that apologies and says how much money the person is short.
1
If you’re interested in knowing more, you should learn about .push(), .unshift(), pop(), splice().
6
JavaScript
var requestAmount = 200;
var totalInAccount = 4200;
if ( requestAmount <= totalInAccount) {
payTheMoney();
} else {
alert('Sorry, you are ' + totalInAccount - requestAmount + ' short.');
}
If there are several options, we can add more “else if...”.
if ( some_condition ) {
do_onething;
} else if ( some_other_condition_is_true ) {
do_anotherThing;
} else {
when_all_else_fails_do_this;
}
There are several comparison operators you should know:
=
set a variable equal to this String or number, e.g., var myNumber = 7;
==
Equal to This checks to see if the variable on the left is equal to the value on the right,
e.g., requestAmount == 300;
!=
Not equal to - the ! is universal for “not”, e.g., if amountRequested != 300
>
Greater than
<
Less than
>=
Greater than or equal to
<=
Less than or equal to
It is very useful to look for ranges and to loop.
Let’s say you want to determine grades; scores >= 89 and <=95 are an ‘A-’. We can compare the variable
(the score) with the ranges. How would you complete this statement?
var studentGrade = 75;
if ( studentGrade >= 89 && studentGrade <= 95) {
alert(“You got an A-”);
}
&& means “and”
|| means “or”
Often you need to make sure the variables have been processed before continuing. Here is an example
that makes sure the user pressed either “n” or “N” before charging out a new book:
if ( (key=’n’) || (key=’N’) ) {
// check out the next book
}
Applying these to your scripts:
7
JavaScript
Imagine writing a script that advises users of your library or archive that starting next Spring they
cannot charge more than 5 items at a time. Let’s say they’ve completed the checkout and are about to
logoff. You want to advise ‘em of the new rule.
Lab Example 2:
<html><head><title>A note about our policy changes ...</title>
</title></head>
<body>
This is a test of JavaScript
<script type="text/javascript">
var name = prompt('What is your name?', '');
</script>
<script type="text/javascript">
var items = prompt('How many items did you check out today?', '');
</script>
<script type="text/javascript">
var limitPerDay = 5;
document.write('<b>Thanks!</b>. We appreciate your coming to the library.);
document.write('Starting next Spring, ' + name +' we will restrict
temporarily borrowing to ');
document.write('no more than '+limitPerDay+' items.');
</script>
</body>
</html>
Looping...
There are two loops that are vital to programming. One is while... and the other is for. A while
statement makes something happen until it is no longer true. For statements continue for a certain
number of iterations.
Let’s say you want to know which printers are on-line. Each printer has its own name so let’s store
them in an array. var printers = ['Lab', ‘Main Office’, ‘Reference Room’, ‘Cataloguing’, ‘Archives’]; And let’s say there’s a
function built-into the printer that tells our program that the printer is ready to be used. The function
returns “true” if the printer is ready; “false” if not.
Lab Example 3:
var num = 0;
var printers = ['Lab', 'Main Office', 'Reference Room', 'Cataloguing', 'Archives'];
while ( num < 5 ) {
if ( isThisPrinterReady( printers[num] ) {
document.write('The printer in ’ + printers[num] + ' is ready.');
} else {
document.write('Sorry, the ' + printer[num] + ' is not yet ready.');
}
}
Notice that the variable “num” has a value of 0. When the while () statement starts, the Interpreter
compares the value of “num” (which is 0) to the limit we used (5). If 0 is less than 5 (which it is!) then
perform the statements between the { and the }. Once inside that area, there’s an if statement. In our
example, some code elsewhere checks that the printer is ready. The results of that checking are not stored
8
JavaScript
in a variable we name but we can still gain access to its value. The if () always equates to something that is
true or false. So, if isThisPrinterReady() returns a value of “true” we tell the user that the printer at index # is
ready, otherwise that is it not ready.
The other most common loop is the “for” statement. The for statement requires 4 things: an initial
condition, something to test, something to do, and a command to update the something to test:
for (some condition; as long as that condition is true; update the condition) {
do this every time and do it before you update the condition;
}
In this example, we want to make the numbers between 0 and 100 appear on the screen.
Learn this: Let’s start with a counter variable (let’s call it “i” for integer). var i = 0; is the “some
condition”;
Next we want to test the condition (as long as i <= 100...)
Next we do the task. In this case it is to print the numbers on the screen.
Finally, we return to the for statement and update the condition: i++
for (var i = 0; i <= 100; i++) {
document.write(“The current number is ”+i);
}
We can use Strings, too:
var days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday', 'Sunday'];
for (var i = 0; i < days.length; i++) {
document.write( days[i] );
}
Finally, it is common to integrate both HTML and JavaScript. Here’s an example where the books someone
has checked out are stored in an array; the call numbers are in an array; and the due dates are in another
array. Since every book, call number, and due date appear in the same order, we can do a lot with very little
work.
var bookTitle = ['Hamlet', 'Macbeth', 'Introduction to Programming', 'Du côté du chez
Swann'];
var callNo = ['B93.223.1 1980', 'B93.224.12 2009', 'QA76.9.4 S9 2010', 'BF13.33.2
1899'];
var dueDate = ['2010-01-01', '2010-01-01', '2010-01-01', '2010-01-01'];
// now we’ll combine HTML’s ordered list tag <ol> and the data from the array:
document.write("<ol>");
for (int i = 0; i < bookTitle.length; i++) {
document.write("<li>" + bookTitle[i] + " " + callNo[i] + " " +
dueDate[i];
}
to create
9
JavaScript
Hamlet
B93.223.1 1980
2010-01-01
Macbeth B93.224.12.2009 2010-01-01
Introduction to Programming QA76.9.4 S9 2010 2010-01-01
Du côté du chez Swann
BF13.3.2 1899
2010-01-01
[Notice that the spacing is not attractive! How would you improve it?]
Functions
Finally, one thing to recall is how code is reused and is passed arguments, or parameters. This is the
structure of a function:
function functionName( any parameters ) {
// the work of the function
}
This function “printToday()” will display the date. Notice that there are no arguments passed to the
function. Notice, too, that the first line of the JavaScript code in the function creates a variable (var), names
it “today”, assigned a value (=), uses the reserve word new (which is what actually causes the computer to
create the object); and calls another function (“Date()”) that returns an object of its own (in this case, the
object is a Date type object that contains today’s date. The date is based on the computer’s system date).
We would like to extract the date from the Date object by converting it into a String that makes sense to
humans (today.toDateString()) and then sending that string to the browser (document.write):
function printToday() {
var today = new Date();
document.write(today.toDateString());
}
Most objects have a built-in method called (“.toString()”) that converts that object into something
people can read (instead of the computer’s cryptic code way of holding data). Because Dates are so
common, there’s an extra kind of method that converts just Dates into what we expect to see a date look
like. This function’s default behavior is to present the date like this: Wed Jul 29 2009. There are ways of
extracting the date and presenting in other ways, too. We will look at those later.
Lab Example 4:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Date Script Demo</title>
<!-- Note: if you want to include your own .css put it here
and remove the comments
<link href="YOURCSS.css" rel="stylesheet" type="text/css">
-->
<script type="text/javascript">
function printToday() {
var today = new Date();
document.write(today.toDateString());
10
JavaScript
}
</script>
</head>
<body>
<h1>A Basic Function</h1>
<p>Today is <strong>
<script type="text/javascript">printToday();
</script>
</strong></p>
</body>
</html>
In this final example, you’ll create an interactive quiz site. You’ll have to think about the functions and how
they work together. You can do it!
Use a text editor that supports UTF-8, such as Apple’s TextEdit or Dreamweaver. Both are available
on GSLIS lab computers. You want to recreate this file - type it in by hand - and save it as .html. As you type
each line be sure to figure out what each line does. Note that the charset=”UTF-8” and that a Chinese
character is included. It doesn’t matter if you cannot read the Chinese or whether it is correct. The point is
to demonstrate the quiz and to experiment. If you enter a Chinese (or Russian or Hindi or any other nonLatin alphabet character) you should be aware that it may not work correctly. [How might you resolve that
problem?] Experiment. After you’re successful running the script, experiment with different questions or
modify the function somehow.
Lab Example 4:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Mini Quiz</title>
<script type="text/javascript">
var score = 0; // initial score is 0
var questions = [
['What is the capital of France', 'Paris'],
['How many moons does Earth have?', 1],
['What does 哦 mean in English?', 'cat']
];
//go through the list of questions and ask each one
for (var i=0; i<questions.length; i++) {
askQuestion(questions[i]);
}
//function for asking question
function askQuestion(question) {
var answer = prompt(question[0],'');
if (answer == question[1]) {
alert('Correct!');
score++;
11
JavaScript
} else {
alert('Sorry. The correct answer is ' + question[1] +'.');
}
}
</script>
</head>
<body>
<h1>A Simple Quiz</h1>
<p>
<script type="text/javascript">
var message = 'You got ' + score;
message += ' out of ' + questions.length;
message += ' questions correct.';
document.write(message);
</script>
</p>
</body>
</html>
______________________________________________________
Assignment
Include and experiment with adding the JavaScript for showing today’s date appear on
your template website.
See also
Many applications expand their functionality by letting the end-user create his or her own
scripts. Here’s a link to Adobe’s Introduction to Scripting for its products. [see Adobe Intro
to Scripting.pdf
There’s also the JavaScript-Notes readings for you to complete. See the syllabus site.
Also see the .js referred to by the class homepage and in the Demo Files area.
12
Download