JavaScript Mini-Tutorial
Michael I. Schwartzbach
Copyright 2001,2002 BRICS, University of
Aarhus
http://www.brics.dk/~mis/ITU/JS/
What is JavaScript?
The date example
The link example
The validation example
The calculation example
The annoying example
The banner example
Components of JavaScript
JavaScript events
Capturing events
Document object model
Navigating the DOM
JavaScript as a language
Basic types and operators
Control structures
Objects
Objects for the DOM
Embedding JavaScript in HTML
PowerForms: compiling into JavaScript
What is JavaScript?
JavaScript is a programming language:
developed by Netscape and SUN in 1995;
has nothing to do with Java (used to be called LiveScript);
programs are executed by the browser.
JavaScript makes HTML pages come alive:
the code is embedded in the HTML document;
it is executed in response to browser events;
it may access and modify the browser state, including the
HTML document;
but the rest of the client's computer is hidden.
Exercises
The date example
JavaScript can be used to dynamically generate parts of a document.
the code looks familar enough;
even the tiniest program is a challenge;
JavaScript is a large language: here are the details about
Date1.
Right now, the date is Mon Jun 2 08:22:12 UTC+0200 2003
The source for this example is:
Right now, the date is
<script type="text/javascript">
document.write(new Date());
</script>
An alternative look is the following:
Right now, the time is 08:22
Here, the source is:
Right now, the time is
<script type="text/javascript">
var now = new Date();
function pad2(i) {
if (i<10) return "0"+i;
return i;
}
document.write(pad2(now.getHours()),":",
pad2(now.getMinutes()));
</script>
Lessons from this example:
http://developer.netscape.com/docs/manuals/js/client/jsref/date.htm#1193137
2
The link example
JavaScript can be used to animate links:
The validation example
JavaScript can be used to restrict the allowed values of
form fields:
The source for this example is:
The source for this example is:
<a href="http://www.brics.dk/bigwig/"
onMouseOver="document.images[4].src='please.gif';"
onMouseOut="document.images[4].src='clickme.gif';">
<img border=0 width=339 height=85
src="clickme.gif">
</a>
Lessons from this example:
tags can respond to mouse events;
the HTML source can be accessed and modified.
The images are created by www.cooltext.com.
<script type="text/javascript">
function checkRange(t,low,high) {
var n = parseInt(t);
if (t!="" && (isNaN(n) || n<low || n>high))
alert("Enter a number between "+low+" and
"+high);
}
</script>
<form>
<input type=text name=number size=10
onBlur="checkRange(this.value,1000,2000);">
</form>
Lessons from this example:
there are many different events;
code can be put into functions.
The calculation example
JavaScript can be used to perform calculations like a
spreadsheet:
The source for this example is:
<script type="text/javascript">
function dollars(n) {
var l = Math.floor(n);
var r = Math.round((100*n)%100);
if (r<10) return "$"+l+".0"+r;
if (r==100) return "$"+(l+1)+".00";
return "$"+l+"."+r;
}
function calculate(f) {
var
amount=f.amount.options[f.amount.selectedIndex].text;
var
price=f.price.options[f.price.selectedIndex].value;
var total=amount*price;
f.total.value=dollars(total);
f.tax.value=dollars(0.25*total);
f.due.value=dollars(1.25*total);
}
</script>
<form>
Buy
<select name=amount>
<option>1
<option>2
<option>5
<option>10
<option>100
<option>1000
</select>
copies at
<select name=price>
<option value="7.23">$7.23
<option value="19.87">$19.87
<option value="45.76">$45.76
</select>
each.
<p>
<table>
<tr><td>
Total cost:</td><td><input type=text name=total
size=8>
</td></tr>
<tr><td>
Sales tax:</td><td><input type=text name=tax
size=8>
</td></tr>
<tr><td>
Amount due:</td><td><input type=text name=due
size=8>
</td></tr>
</table>
<p>
<input type=button value=Calculate
onClick="calculate(this.form);">
</form>
Lessons learned from this example:
navigation in the HTML source is tricky;
it all comes down to ordinary programming.
The annoying example
JavaScript can be used to really annoy people:
The banner example
JavaScript can be used to create simple animations:
The source for this example is:
<html>
<head>
<title>MAKE MONEY FAST!</title>
</head>
<script type="text/javascript">
var nice=false;
function popUp() {
if (!nice)
window.open("money.html","","height=100,width=400");
}
</script>
<body onUnload="popUp();popUp();">
<h1>MAKE MONEY FAST!</h1>
<form>
<input type=button value="Be nice"
onClick="nice=true;">
</form>
</body>
</html>
Lessons learned from this example:
be careful of JavaScript;
browser windows have local state.
Web Programming is k00l...
The source for this example is:
<script type="text/javascript">
var message = "Web Programming is k00l...";
var delay = 150;
var width = 40+message.length;
var pos = 0;
for (var i=0; i<40; i++) message = " " + message;
function scroll() {
document.forms[0].banner.value=
message.substring(pos,width)
+message.substring(0,pos-1);
pos = (pos+1)%width;
setTimeout("scroll();",delay);
}
</script>
<body onLoad="scroll();">
<form>
<input name=banner type=text size=40>
</form>
</body>
Lessons learned from this example:
events can be scheduled for the future;
solutions are built out of whatever is available.
Components of JavaScript
JavaScript has three main components:
a programming language for expressing the
scripts;
a Document Object Model (DOM) for representing
the browser state;
a collection of events associated with different
HTML tags.
The programming language:
has all the usual standard features;
is object-based, not object-oriented;
relies on a huge library of predefined objects.
The Document Object Model:
represents the browser state, i.e. the history,
document, and location;
gives access to every part of the document;
allows scripts to make arbitrary modifications.
The events are caused by:
the browser, e.g. loading a new document;
the users, e.g. typing and using the mouse;
timeouts, e.g. every 150 milliseconds.
JavaScript events
The events capture most things that can happen.
Event
Applies to
Occurs when
Event
handler
Abort
images
User aborts the
loading of an image
(for example by
clicking a link or
clicking the Stop
button)
onAbort
Blur
windows and all form User removes input
elements
focus from window
or form element
onBlur
Change
text fields, textareas, User changes value
select lists
of element
onChange
Click
buttons, radio
buttons,
checkboxes, submit
buttons, reset
buttons, links
User clicks form
element or link
onClick
DragDrop
windows
User drops an object onDragDrop
onto the browser
window, such as
dropping a file on
the browser window
Error
Images,
The loading of a
onError
windows
document or image
causes an error
Reset
forms
User resets a form
(clicks a Reset
button)
onReset
windows and all
form elements
User gives input
focus to window or
form element
onFocus
Resize
windows
User or script
resizes a window
onResize
KeyDown
documents,
images, links,
text areas
User depresses a
key
onKeyDown
Select
text fields,
textareas
User selects form
element's input
field
onSelect
KeyPress
documents,
images, links,
text areas
User presses or
holds down a key
onKeyPress
Submit
forms
User submits a
form
onSubmit
KeyUp
Unload
document body
User exits the page onUnload
documents,
images, links,
text areas
User releases a
key
onKeyUp
Load
document body
User loads the
page in the
Navigator
onLoad
MouseDown
documents,
buttons, links
User depresses a
mouse button
onMouseDown
MouseMove
nothing by
default
User moves the
cursor
onMouseMove
MouseOut
areas, links
User moves cursor
out of a client-side
image map or link
onMouseOut
MouseOver
links
User moves cursor
over a link
onMouseOver
MouseUp
documents,
buttons, links
User releases a
mouse button
onMouseUp
Move
windows
User or script
moves a window
onMove
Focus
Capturing events
Each HTML tags has some of the events associated to it.
For the input tag of type text, the relevant events are:
onBlur
onChange
onFocus
They are illustrated by the following examples:
onBlur
onChange
onFocus
for which the source is:
<form>
<input type=text value="onBlur" onBlur="alert('You
blurred me!');">
<input type=text value="onChange"
onChange="alert('You changed me!');">
<input type=text value="onFocus"
onFocus="alert('You focused me!');">
</form>
For the input tag of type checkbox, the relevant events are:
onBlur
onClick
onFocus
for which the source is:
<script>
var c=false;
var t=false;
var a=false;
function update(x) {
var s = "Pizza with";
if (x=="cheese") c=!c;
if (x=="tomato") t=!t;
if (x=="anchovy") a=!a;
if (c) s = s + " cheese";
if (t) {
if (c) s = s + " and";
s = s + " tomata";
}
if (a) {
if (c || t) s = s + " and";
s = s + " anchovy";
}
if (!c && !t && !a) s = s + " nothing";
document.forms[1].bar.value=s;
}
</script>
<form>
<input type=checkbox name=foo value=cheese
onClick="update('cheese');">
Cheese
<input type=checkbox name=foo value=tomato
OnClick="update('tomato');">
Tomato
<input type=checkbox name=foo value=anchovy
OnClick="update('anchovy');">
Anchovy
<input type=submit name=bar value="Pizza with
nothing">
</form>
They are illustrated by the following examples:
Document object model
The JavaScript document object model describes the
browser state:
Navigating the DOM
Every attribute of the current HTML can be reached by
some JavaScript expression.
Here are some basic examples for this current document:
document.title
JavaScript: navigating the DOM
document.bgColor
#ffffff
document.images[0].src
http://www.brics.dk/~mis/ITU/home.gif
document.images[3].src
http://www.brics.dk/~mis/ITU/right.gif
document.images[3].height
30
document.images[3].border
document.links[0].href
http://www.brics.dk/~mis/ITU/JS/index.html
document.links[2].href
http://www.brics.dk/~mis/ITU/JS/dom.html
If we define a form:
This is not a p
then more interesting expressions are available:
This is used to access and modify the attributes of many
markup tags in the current HTML document.
document.forms[0].elements.length
document.forms[0].elements[0].type
select-one
document.forms[0].elements[0].name
language
document.forms[0].language.options.length
document.forms[0].language.options[0].text
Danish
document.forms[0].language.options.selectedIndex 1
document.forms[0].elements[1].type
text
document.forms[0].elements[1].name
phrase
document.forms[0].phrase.value
This is not a pipe
document.forms[0].phrase.value.length
18
document.forms[0].phrase.value.charAt(10)
JavaScript as a language
JavaScript has a familiar syntax:
sort of like C and Java;
easy to learn for most programmers.
JavaScript is object-based:
objects are like boxes with named contents;
not object-oriented (no classes).
JavaScript is dynamically typed:
type errors are only detected at runtime;
liberal defaults and coercions confuse the picture.
JavaScript has lots of online documentation:
the Netscape JavaScript Reference2;
the Netscape JavaScript Guide3;
javascript tuto search
In particular, look at these 100 examples4.
Basic types and operators
JavaScript has the following types of values:
numbers;
boolean values;
strings;
null;
arrays;
objects.
The following program uses the simpler types and shows
some common operators:
<script type="text/javascript">
var f = 0;
var g = 1;
document.write("Here are some Fibonacci
numbers:<br>");
var fib = [];
fib[50] = 0;
for (var i=0; i<50; i++) {
fib[i]=f;
var h = g;
g = f + g;
f = h;
}
for (var i=0; i<50; i++) {
document.write("fib["+i+"] = "+fib[i]+"<br>");
}
document.write("The golden ration is almost "+
(fib[49]/fib[48]));
</script>
http://developer.netscape.com/docs/manuals/js/client/jsref/index.htm
http://developer.netscape.com/docs/manuals/js/client/jsguide/index.htm
4
http://www.w3schools.com/js/js_examples.asp
3
10
It generates the following output:
Here are some Fibonacci numbers:
fib[0] = 0
fib[1] = 1
fib[2] = 1
fib[3] = 2
fib[4] = 3
fib[5] = 5
fib[6] = 8
fib[7] = 13
fib[8] = 21
fib[9] = 34
fib[10] = 55
fib[11] = 89
fib[12] = 144
fib[13] = 233
fib[14] = 377
fib[15] = 610
fib[16] = 987
fib[17] = 1597
fib[18] = 2584
fib[19] = 4181
fib[20] = 6765
fib[21] = 10946
fib[22] = 17711
fib[23] = 28657
fib[24] = 46368
fib[25] = 75025
fib[26] = 121393
fib[27] = 196418
fib[28] = 317811
fib[29] = 514229
fib[30] = 832040
fib[31] = 1346269
fib[32] = 2178309
fib[33] = 3524578
fib[34] = 5702887
fib[35] = 9227465
fib[36] = 14930352
fib[37] = 24157817
fib[38] = 39088169
fib[39] = 63245986
fib[40] = 102334155
fib[41] = 165580141
fib[42] = 267914296
fib[43] = 433494437
fib[44] = 701408733
fib[45] = 1134903170
fib[46] = 1836311903
fib[47] = 2971215073
fib[48] = 4807526976
fib[49] = 7778742049
The golden ration is almost 1.618033988749895
11
Control structures
JavaScript supports the usual control structures:
the conditionals if, if...else, and switch;
the iterations for, while, do...while, break, and
continue;
functions.
They look and behave the same as in C or Java.
The following program:
<script type="text/javascript">
function Hanoi(a,b,c,n) {
if (n>0) {
Hanoi(a,c,b,n-1);
document.write("Move a disk from "+a+" to
"+c+"<br>");
Hanoi(b,a,c,n-1);
}
}
Hanoi("A","B","C",8);
</script>
Objects
JavaScript objects are simple maps from names to:
values (properties);
functions (methods);
Properties and methods can change at any time:
added by assigning to a new name;
removed by assigning null to the name.
An new object is created by:
writing an object constant;
using a constructor function.
There is a collection of predefined objects:
Array;
Boolean;
Date;
Function;
Math;
Number;
RegExp;
String.
The following program:
<script type="text/javascript">
var x = {name:"Donald Duck",species:"duck",age:67};
document.write(x.name,"<br>");
function Cartoon(name,species,age) {
this.name = name;
this.species = species;
this.age = age;
}
var y = new Cartoon("Donald Duck","duck",67);
12
Objects for the DOM
document.write(y.species,"<br>");
function celebrate() {
this.age++;
document.write("Happy Birthday,
"+this.name,"<br>");
}
y.birthday = celebrate;
y.birthday();
document.write(y.age,"<br>");
</script>
All HTML form tags are represented as special object in
JavaScripts.
generates this output:
As a special case, a DOM object may also be viewed as an
array.
Donald Duck
duck
Happy Birthday, Donald Duck
68
Navigating through the DOM corresponds to selecting
properties in these objects.
The navigation:
document.forms[0].elements[0].type
is justified since:
their is a predefined Document object called document;
the Document object has a forms property, which is an
array of Form objects;
the Form object has an elements property which is an
array of DOM objects;
each DOM object has a type property.
13
Embedding JavaScript in
HTML
Powerforms: compiling into
JavaScript
JavaScript may at any place in an HTML document be
embedded as:
JavaScript code for complicated form validation can be
automatically generated by the PowerForms tool.
<script type="text/javascript">
...
</script>
The following examples show some of the possibilities:
To protect older browser, the code is sometimes put into
parentheses:
<script type="text/javascript">
<!-...
-->
</script>
JavaScript is executed when the browser meets this tag.
A piece of JavaScript code can only see:
the JavaScript declarations that have previously
been executed;
the part of the DOM that has already been rendered.
Name:
E-mail:
Country:
Zip code:
Phone:
Request visit from NYC office
OK
Cancel
The PowerForms takes as input NYC.html and NYC.pwf and
generates lots of JavaScript.
JavaScript code can also appear in event handlers for
HTML tags, which is only executed when the event is
triggered.
14
Exercises
Optional Hand-In
1. Change the validation example to accept only even
numbers. Hint: a number n is even if n%2==0.
2. Modify the date example to work like a clock. Hint: to
update a text with JavaScript, it must appear in a
button or a text field. Another hint: show seconds as
well, or your clock will not be that interesting (in
particular, you will stare at your screen wondering
why your code doesn't work :-).
3. Use the link example to create a menu, where the
items change color when the mouse hovers over an
entry. Use these images as menu items: light1,
dark1, light2, dark2, light3, dark3.
4. View the sources of www.jubii.dk and www.time.com.
Try to understand what they use JavaScript for.
5. Look at the following form:
I have a cat
I have a rabbit
A Web shop wants to sell ice cream online. They
offer 5 different kinds of toppings: sprinkles,
chocolate chips, strawberry syrup, banana flakes,
and caramel sauce. Toppings are chosen using 5
checkboxes. However, some constraints apply:
1. at most three toppings may be selected
2. strawberry syrup and caramel sauce cannot
both be chosen (too messy!)
These constraints must be enforced by JavaScript
code. Discuss (briefly) the various design aspects
and program a solution.
I have a gorilla
Select pet food:
6. Clearly, some food items are irrelevant for some
pets. Use JavaScript to restrict the menu
appropriately once the pet has been selected. Hint:
the appropriate menu options must be copied to a
new array which is then assigned to the select
object.
7. Use JavaScript to make a calculator tool. Represent
the calculator buttons by input buttons and the
display by a text field.
15